class A{
private static $instance;
public static function getInstance(){
if(!(self::$instance instanceof self))
self::$instance = new self();
return self::$instance;
}
public function doStuff(){
echo 'stuff';
}
}
class B extends A{
public function doStuff(){
echo 'other stuff';
}
}
A::getInstance()->doStuff(); // prints "stuff"
B::getInstance()->doStuff(); // prints "stuff" instead of 'other stuff';
What am I doing wrong?
Why doesn’t class B run it’s function?
Look at the code in
getInstance:All those
selfs point toA, not to the class that was called. PHP 5.3 introduces something called “late static binding”, which allows you to point to the class that was called, not to the class where the code exists. You need to use thestatickeyword:Unfortunately, this will fail if you don’t have PHP 5.3 at least.