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 using static::
, but not when used with $this->
or self::
. I don't know of a way to get it to return B
short of having the echo within B
instead of A
. It sounds like this would be an ideal use of traits if you were using PHP 5.4.
Example:
class A
{
public static function doSomething()
{
echo __CLASS__;
}
}
class B extends A
{
public static function doMore()
{
self::doSomething();
}
}
class C extends B {}
C::doMore();
This returns A
instead of C
.