April 18, 2012

PHP: get_called_class() returns unexpected value

Question by J.S.

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

Answer by Starx

Override the method doSomething, to get B

class C extends B
{
    public static function doMore()
    {
        B::doMore();
    }
}

Tested

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!