PHP使用同一类中的call_user_func调用实例方法 [英] PHP Call a instance method with call_user_func within the same class

查看:193
本文介绍了PHP使用同一类中的call_user_func调用实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用call_user_func从同一个对象的另一个方法中调用一个方法,例如

I'm trying to use call_user_func to call a method from another method of the same object, e.g.

class MyClass
{
    public function __construct()
    {
        $this->foo('bar');
    }
    public function foo($method)
    {
        return call_user_func(array($this, $method), 'Hello World');
    }

    public function bar($message)
    {
        echo $message;
    }
}

new MyClass;应该返回"Hello World" ...

new MyClass; Should return 'Hello World'...

有人知道实现这一目标的正确方法吗?

Does anyone know the correct way to achieve this?

非常感谢!

推荐答案

您发布的代码应该可以正常工作.一种替代方法是像这样使用变量函数" :

The code you posted should work just fine. An alternative would be to use "variable functions" like this:

public function foo($method)
{
     //safety first - you might not need this if the $method
     //parameter is tightly controlled....
     if (method_exists($this, $method))
     {
         return $this->$method('Hello World');
     }
     else
     {
         //oh dear - handle this situation in whatever way
         //is appropriate
         return null;
     }
}

这篇关于PHP使用同一类中的call_user_func调用实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆