I’ve never seen code like this:
public static function getInstance()
{
if ( ! isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
Is it the same as new className() ?
EDIT
If the class is inheritant,which class does it point to?
selfpoints to the class in which it is written.So, if your getInstance method is in a class name
MyClass, the following line :Will do the same as :
Edit : a bit more information, after the comments.
If you have two classes that extend each other, you have two situations :
getInstanceis defined in the child classgetInstanceis defined in the parent classThe first situation would look like this (I’ve removed all non-necessary code, for this example — you’ll have to add it back to get the singleton behavior)* :
Here, you’ll get :
Which means
selfmeansMyChildClass— i.e. the class in which it is written.For the second situation, the code would look like this :
And you’d get this kind of output :
Which means
selfmeansMyParentClass— i.e. here too, the class in which it is written.With PHP That’s why PHP 5.3 introduces a new usage for the
statickeyword : it can now be used exactly where we usedselfin those examples :But, with
staticinstead ofself, you’ll now get :Which means that
staticsort of points to the class that is used (we usedMyChildClass::getInstance()), and not the one in which it is written.Of course, the behavior of
selfhas not been changed, to not break existing applications — PHP 5.3 just added a new behavior, recycling thestatickeyword.And, speaking about PHP 5.3, you might want to take a look at the [Late Static Bindings][1] page of the PHP manual.