3

I'm a PHP newbie. Here is a standart Singleton pattern example according to phptherightway.com:

<?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) 

The question is in this line:

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

So as i understand if (null === $instance) is always TRUE, because everytime i'm calling the method getInstance() the variable $instance is always being set to null and a new instance will be always created. So this is not really a singleton. Could you please explain me ?

2
  • 1
    Just in case stackoverflow.com/questions/8776788/… Commented Oct 30, 2014 at 7:24
  • 2
    static $instance = null; will be executed only on first function call - at others it will be ignored Commented Oct 30, 2014 at 7:40

2 Answers 2

2

Look at "Example #5 Example use of static variables" here: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

"Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it."

Sign up to request clarification or add additional context in comments.

Comments

1

See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

static $instance = null; 

will be runned only on first function invoke

Now, $a is initialized only in first call of function

and all other time it will store created object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.