misfit
misfit

Reputation: 107

Singleton pattern example in PHP

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 ?

Upvotes: 3

Views: 1774

Answers (2)

martindilling
martindilling

Reputation: 2929

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."

Upvotes: 2

user3423805
user3423805

Reputation:

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

Upvotes: 1

Related Questions