Sunday 15 September 2013

oop - Singleton pattern example in PHP -



oop - Singleton pattern example in PHP -

i'm php newbie. here standart singleton pattern illustration according phptherightway.com:

<?php class singleton { public static function getinstance() { static $instance = null; if (null === $instance) { $instance = new static(); } homecoming $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)

the question in line:

static $instance = null; if (null === $instance) { $instance = new static(); }

so understand if (null === $instance) true, because everytime i'm calling method getinstance() variable $instance beingness set null , new instance created. not singleton. please explain me ?

look @ "example #5 illustration utilize of static variables" here: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

"now, $a initialized in first phone call of function , every time test() function called print value of $a , increment it."

php oop design-patterns singleton

No comments:

Post a Comment