PHP:类与实例变量(PHP: Class vs Instance variables)

我知道Java和C#等编程语言中的类变量和实例变量存在差异,所以我想知道PHP是否相同。

所以我知道类变量在该类的所有实例之间共享,而实例变量仅与该类的特定实例相关。

例如:

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 }

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 }

最满意答案

PHP具有静态类属性 。 代码中的所有属性都不会声明为静态,因此它们都是实例属性。

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

更多推荐