2
class A
{
    public static function who1()
    {
        var_dump(get_called_class());
    }
}
class B extends A
{
    public static function who2()
    {
        parent::who1();
    }
}
call_user_func(array('B', 'parent::who1'));
B::who2();

What I expect:

string 'B' (length=1)

string 'B' (length=1)

Actual returns:

boolean false

string 'B' (length=1)

Can anyone tell me why the output is different from what I expected?

see also:

https://www.php.net/manual/en/language.types.callable.php

https://www.php.net/manual/en/function.get-called-class.php

edit: Maybe my old code is not clear, here is the new example:

class A
{
    public static function who()
    {
        var_dump(get_called_class());
    }
}
class B extends A
{
    public static function who()
    {
        echo 'hehe';
    }
}
call_user_func(array('B', 'parent::who'));

why it output false?

2
  • 2
    You don't need to add the parent part in the call to parent::who1. Have a look at php.net/manual/en/language.oop5.inheritance.php: For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality. Commented Feb 15, 2014 at 17:35
  • Don't use parent::: call_user_func(array('B', 'who1')); Commented Feb 15, 2014 at 17:36

1 Answer 1

2

From the PHP manual documentation for Object Inheritance:

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

As stated above, there is no need of parent prefix there in call_user_func():

call_user_func(array('B', 'who'));

You got FALSE in var_dump() because call_user_func() stated method call outside a class. So get_called_class() behaved as expected (or mentioned in the manual):

Returns FALSE if called from outside a class.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't get it. get_called_class() is still inside method who(), who() is inside class A. If I call it like this A::who(); it will output A.
@nut get_called_class() probably in this case can not properly determine caller class. And this seems like a bug to me. Looks like call_user_func(array('B', 'parent::who')); forces ::who() to be called outside a class scope.
Yea, my example seems complex, I will post it on bug list to get the detailed information. And thanks for mention Object Inheritance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.