php - 我可以在 PHP 中调用没有名称的继承父方法吗?

标签 php inheritance

有没有办法在不指定函数名称的情况下调用继承的方法?

类似于:

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/

相关文章:

c++ - 绕过基类构造函数调用

javascript - 如何使用backbone.js的多态性,特别是super的属性?

C++ 使用类标记数学表达式

php - 如何测试 ZF2 服务

php - 如何返回字符串是属性子字符串的所有行

php - 如何从命令行执行 PHP 代码?

c++ - 如何在 C 中使用 printf 查找对象类型?

javascript - 无法将数据库中的数据与字符串数组进行比较

php - 无法在 Codeigniter 中发送电子邮件,没有错误消息。本地或远程

javascript - 你能用 jquery 获取继承的元素类吗?