Sample Singleton Pattern in PHP

I am new to PHP. Here is a standard example of a Singleton pattern 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 on this line:

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

      

Since I understand it is if (null === $instance)

always TRUE because every time I call the method the getInstance()

variable is $instance

always set to null

and a new instance will be created. So this is not a singleton. Can you explain to me?

+3


source to share


2 answers


Take a look at "Example # 5 Static Variable Usage Example" here: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static



"Now $ a is initialized only the first time the function is called, and every time the test () function is called, it prints the value of $ a and increments it."

+2


source


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

static $instance = null;

      

will only run on the first invoke function



Now $ a is initialized only on the first call of the function

and at other times it will save the created object

+1


source







All Articles