I found this function in some code being advocated as 'good' on another SE site.
public static function init()
{
is_null( self::$instance ) AND self::$instance = new self;
return self::$instance;
}
Can someone explain this line in english for me?
is_null( self::$instance ) AND self::$instance = new self;
I am not interested in hearing why you think singletons
are bad. I'm aware this code is designed to return an instance of the containing class but I just don't understand how to read that one line. What is the result of self::$instance = new self;
?
That is perfectly clean code. The line first tests if the singleton already exists, if so it is returned. If not, then a new instance is created, stored inside the singletons class static instance attribute and returned.
One might stumble about the unconventional notation using the AND
operator. But that is perfectly valid PHP code: The part behind the AND
is only executed if the condition before is true So if not object exists in this case.
The result (return value) of the assignment of the construct self::$instance = new self
is irrelevant here. It has fulfilled its duty, the object is created. I personally would prefer this construct to be written inside backets. But in general the assignment operator also has a return value when evaluated in this way. This is why you can also make very clean code using this construction: if (FALSE===($result=action())) {do_something();}
.
The result of self::$instance = new self;
is that the static $instance
variable gets initialized by the current object (as it didn't exist beforehand).
It basically means that if self:$instance
is null
, make self:$instance
new self
.
A more verbose method would be:
if(is_null(self::$instance)){
self::$instance = new self;
}
To answer your actual question, the result of self::$instance = new self;
would be true
, but that's irrelevant because we're just using it to assign the variable itself.