static instance in PHP
Why does the following code print "1,1,1," instead of "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();
}
$instance
is a local variable, not a static class property. Unlike Java you always must access variables, or properties in theire scope
$var; // local variable
$this->var; // object property
self::$var; // class property
I just saw
// singleton instance
The singleton pattern is usually implemented different
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();
The singleton pattern ensures, that you always interact with exactly one instance of a class.
In your constructor, $instance
is not yet defined. You must use:
self::$instance++;
echo self::$instance . ",";
to reference the static property of your class.
精彩评论