Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 943
misfit Avatar asked Jun 30 '26 14:06

misfit


2 Answers

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

like image 82
martindilling Avatar answered Jul 02 '26 04:07

martindilling


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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!