Я новичок в PHP. Вот стандартный пример Singleton шаблон согласно phptherightway.com:Пример шаблона Singleton в PHP
<?php
class Singleton
{
public static function getInstance()
{
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct()
{
}
private function __clone()
{
}
private function __wakeup()
{
}
}
class SingletonChild extends Singleton
{
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance()); // bool(true)
$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance()); // bool(false)
var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)
Вопрос заключается в этой строке:
static $instance = null;
if (null === $instance) {
$instance = new static();
}
Итак, как я понимаю, if (null === $instance)
всегда TRUE, потому что каждый раз я звоню метод getInstance()
переменная $instance
всегда устанавливается в null
, и будет создан новый экземпляр. Так что это не синглтон. Не могли бы вы объяснить мне?
На всякий случай http://stackoverflow.com/questions/8776788/best-practice-on-php-singleton-classes –
static $ instance = null; будет выполняться только при первом вызове функции - в других он будет проигнорирован –