3

I know there is a difference in class variables and instance variables in programming languages like Java and C#, so I was wondering if PHP is the same.

So I know class variables is shared among all the instances of that class whereas instance variables is only relevant to that specific instance of that class.

For example:

class db {
  private $host;   <--
  private $user;   <-- These will be treated as instance variables
  private $pass;   <-- as they are set by the class constructor
  private $dbname; <--

  private $connected = false; <-- Will this be treated as a class 
                                  variable? Shared among all the 
                                  instance of the db class?

  public function __construct($host, $user, $pass, $dbname) {
    $this->host = $host;
    $this->user = $user;
    $this->pass = $pass;
    $this->dbname = $dbname;
  }

  public function checkConn() {
    // some code here to change the value of $this->connected
  }

1 Answer 1

6

PHP has static class properties. None of the properties in your code are declared as static, so they all are instance properties.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing me in the right direction this is exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.