PHP中的静态实例

4
以下代码为什么输出“1,1,1,”而不是“4,5,6,”?

class MyClass {
  // singleton instance
  private static $instance = 3;

  function __construct() {
 $instance++;
 echo $instance . ",";
  }
}

for($i = 0; $i < 3; $i++) {
 $obj = new MyClass();
}
2个回答

12

$instance 是一个局部变量,而不是一个静态类属性。与 Java 不同,你必须始终在其作用域内访问变量或属性。

$var; // local variable
$this->var; // object property
self::$var; // class property

我刚刚看到

// singleton instance

单例模式通常有不同的实现方式。

class SingletonClass {
    protected $instance = null;
    protected $var = 3;
    protected __construct () {}
    protected __clone() {}
    public static function getInstance () {
        if (is_null(self::$instance)) { self::$instance = new self(); }
        return self::$instance;
    }
    public function doSomething () {
        $this->var++;
        echo $this->var;
    }
}
$a = SingletonClass::getInstance();
$a->doSomething();

单例模式确保您始终与类的一个实例进行交互。


3
在你的构造函数中,$instance 还没有被定义。你必须使用以下代码:
self::$instance++;
echo self::$instance . ",";

引用您的类的静态属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接