Singleton design pattern I am a beginner in PHP-OOP and design patterns. I have got this basic piece of code in Singleton Pattern and I changed it in order to understand its behavior. I can see that it works as expected.

However, it is not clear for me exactly how it works. Can anyone explain me? So it is working! My doubt is "Whis $inst is not always null in the if since I am defining it null before entering the if"?

&lt;?php

final class UserFactory // "final" prevents child classes from overriding a method by prefixing the definition
{
    private $state=1;

    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    private function __construct()
    {

    }

    public function addToState(){
        $this-&gt;state=$this-&gt;state+1;
    }
    public function getState(){
        return $this-&gt;state;
    }
}

// $myFactory=new UserFactory(); //Throws an error

$myFactory=UserFactory::Instance();
print_r($myFactory);

echo "&lt;br&gt;";
echo 'myState: '.$myFactory-&gt;getState()."&lt;br&gt;";

$myFactory-&gt;addToState();

echo 'myState: '.$myFactory-&gt;getState()."&lt;br&gt;";

$myFactory2=UserFactory::Instance();
print_r($myFactory2);



?&gt;


The output is:

UserFactory Object ( [state:UserFactory:private] =&gt; 1 )
myState: 1
myState: 2
UserFactory Object ( [state:UserFactory:private] =&gt; 2 ) UserFactory Object ( [state:UserFactory:private] =&gt; 2 )
You're misunderstanding how the static keyword works.

The first time it is encountered for a specific variable in the method it defines the $inst variable as null, then checks to see if it is null (it is :p) and then sets it to a new object of that class.

The second time, the static definition isn't used because the static variable has already been defined. It then checks to see if it is null, it isn't, it has already been set to a new object of the class, so it skips the if and returns the object.