Frage

I am trying to understand how this Singleton implementation works.

final class UserFactory
{
    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            echo "inst was null \n";
            $inst = new UserFactory();
        }
        else {
            echo "inst was not null this time \n";
        }
        return $inst;
    }

    /**
     * Private ctor so nobody else can instance it
     *
     */
    private function __construct()
    {

    }
}

echo "get user1 \n";
$user1 = UserFactory::Instance();
echo "get user2 \n";
$user2 = UserFactory::Instance();

if ($user1 === $user2){
    echo "they are the same obj \n";
}

Which outputs the following:

get user1 
inst was null 
get user2 
inst was not null this time 
they are the same obj 

I dont understand why the first time $inst is initialised as null and the $inst === null test passes but the same does not happens on later calls.

War es hilfreich?

Lösung

That is because $inst was declared as a static variable.. If you remove the static keyword , then you will get null the second time.

From the PHP Docs..

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top