PHP中的静态实例

Can*_*ner 3 php

为什么以下代码打印"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();
}
Run Code Online (Sandbox Code Playgroud)

Kin*_*nch 11

$instance是一个局部变量,而不是静态类属性.与Java不同,您始终必须访问该范围内的变量或属性

$var; // local variable
$this->var; // object property
self::$var; // class property
Run Code Online (Sandbox Code Playgroud)

我刚看到

// singleton instance
Run Code Online (Sandbox Code Playgroud)

单例模式通常实现不同

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();
Run Code Online (Sandbox Code Playgroud)

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