HiveBrain v1.2.0
Get Started
← Back to all entries
principlephpMinor

Singleton design pattern

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
designsingletonpattern

Problem

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

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

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

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

echo "";
echo 'myState: '.$myFactory->getState()."";

$myFactory->addToState();

echo 'myState: '.$myFactory->getState()."";

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

?>


The output is:

UserFactory Object ( [state:UserFactory:private] => 1 )
myState: 1
myState: 2
UserFactory Object ( [state:UserFactory:private] => 2 ) UserFactory Object ( [state:UserFactory:private] => 2 )

Solution

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.

Context

StackExchange Code Review Q#42771, answer score: 8

Revisions (0)

No revisions yet.