Using PHP 5.3+ and having something equal to the following I get the output of ‘C’ instead of ‘B’:
class A
{
public static function doSomething()
{
echo get_called_class();
}
}
class B extends A
{
public static function doMore()
{
self::doSomething();
}
}
class C extends B {}
C::doMore();
If I had used static::doSomething() that would be the expected result, but when using self::doSomething() I expect this method to get called in the scope of B because it’s where the ‘self’ is defined and not the late static binding.
How is that explained and how do I get ‘B’ in the doSomething() method?
Thanks in advance, JS
The issue here is late static binding. The
get_called_class()function will use late static binding to return the class name,__CLASS__will use late static binding if called usingstatic::, but not when used with$this->orself::. I don’t know of a way to get it to returnBshort of having the echo withinBinstead ofA. It sounds like this would be an ideal use of traits if you were using PHP 5.4.Example:
This returns
Ainstead ofC.