有没有办法在不指定函数名称的情况下调用继承的方法?
类似于:
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;
}
}
我可以想到使用 debug_backtrace()
来执行此操作,获取调用 inherit() 的最后一个函数,并使用相同的函数名称访问它的父函数。我想知道是否有更好的方法来代替使用显然不适合此目的的调试功能。
最佳答案
您可以使用 magic __FUNCTION__
constant.
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"
代替
call_user_func(array('parent', __FUNCTION__));
你还可以
parent::{__FUNCTION__}();
关于php - 我可以在 PHP 中调用没有名称的继承父方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947881/