有没有办法调用一个继承的方法,而不指定它的函数名?
就像是:
class Child extends Parent {
function some_function(){
// magically inherit without naming the parent function
// it will call parent::some_function()
parent::inherit();
// other code
}
function another_function(){
// it will call parent::another_function()
$result = parent::inherit();
// other code
return $result;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以想到使用hack来执行此操作debug_backtrace(),获取调用inherit()的最后一个函数,并使用相同的函数名访问它的父级.我想知道是否有更好的方法而不是使用显然不适用于此的调试功能.
你可以使用魔法__FUNCTION__常数.
class A
{
function some_function()
{
echo 'called ' . __METHOD__;
}
}
class B extends A
{
function some_function()
{
call_user_func(array('parent', __FUNCTION__));
}
}
$b = new B;
$b->some_function(); // prints "called A::some_function"
Run Code Online (Sandbox Code Playgroud)
代替
call_user_func(array('parent', __FUNCTION__));
Run Code Online (Sandbox Code Playgroud)
你也可以
parent::{__FUNCTION__}();
Run Code Online (Sandbox Code Playgroud)