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();
}
+3
source share
2 answers

$instanceis a local variable, not a static property of a class. Unlike Java, you should always refer to variables or properties in scope

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

I just saw

// singleton instance

A singleton pattern typically uses 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 syntax template ensures that you always interact with one instance of the class.

+10
source

$instanceNot yet defined in your constructor . You should use:

self::$instance++;
echo self::$instance . ",";

to reference the static property of your class.

+3
source

Source: https://habr.com/ru/post/1777421/


All Articles