【问题标题】:PHP: Class vs Instance variablesPHP:类与实例变量
【发布时间】:2016-05-24 20:37:59
【问题描述】:

我知道在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
  }

【问题讨论】:

    标签: php oop


    【解决方案1】:

    PHP 有static class properties。您的代码中没有任何属性被声明为静态的,因此它们都是实例属性。

    【讨论】:

    • 感谢您为我指明正确的方向this 正是我想要的。
    猜你喜欢
    • 2014-09-21
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2020-10-14
    • 2012-10-06
    • 2016-11-17
    相关资源
    最近更新 更多