PHP在同一个类中使用call_user_func调用实例方法

Fre*_*red 22 php

我试图用来call_user_func从同一个对象的另一个方法调用一个方法,例如

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

new MyClass; 应该回归'Hello World'......

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

非常感谢!

Pau*_*xon 26

您发布的代码应该可以正常工作.另一种方法是使用"变量函数",如下所示:

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;
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 我会对此略微皱眉,因为如果该方法不存在会引发致命错误,但可以安全地假设在其他地方进行检查 (4认同)
  • @pekka:对我来说这是**总是**包装在检查`method_exists($ obj,$ method)`或`is_callable`取决于用法. (2认同)

Mat*_*son 15

这对我有用:

<?php
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;
    }
}

$mc = new MyClass();
?>
Run Code Online (Sandbox Code Playgroud)

打印出来:

wraith:Downloads mwilliamson$ php userfunc_test.php 
    Hello World
Run Code Online (Sandbox Code Playgroud)