Disclaimer
I want to warn you in advance that this is not a topic for another holivar - I have been working in PHP for quite some time and quite successfully. But all this is only because this language is very common and probably out of habit;) But very often there are moments in my practice when you realize that this language is far from perfect.
So we are looking forward to PHP6 :)
Meanwhile, do not judge strictly and do not rush to minus my karma - this is my first habratopic
Actually the problem
The task was quite ordinary - it was necessary to use the
Singleton pattern
for a certain number of classes. It's clear that there is no reason to do this for each class separately, and why should there be any inheritance!
A couple of minutes and - voila - everything ingenious is simple:
class static_base {
static $ instance = null;
static function instance () {
if (! self :: $ instance)
self :: $ instance = new self ();
return self :: $ instance;
}
};
class static_A extends static_base {};
class static_B extends static_base {};
static_A :: instance ();
static_B :: instance ();
But it was not there! I forgot that this is PHP5.2.4. What do you think - what is the result of this code? Nizachto not guess - both calls return the same object, and the class
static_base
!
That's how people believe after that.
As it turned out, the self
modifier is substituted in PHP at the stage of parsing the code, so there is no difference in the call to
static_A::instance()
and
static_base::instance()
.
It's good that this was fixed in PHP5.3 by introducing the
static
modifier along with
self