Reputation: 1473
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?
Upvotes: 2
Views: 892
Reputation: 12168
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.
Upvotes: 2