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

时间:2010-11-26 19:36:26

标签: 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;
    }
}

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

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

非常感谢!

3 个答案:

答案 0 :(得分:26)

您发布的代码应该可以正常运行。另一种方法是使用"variable functions",如下所示:

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

答案 1 :(得分:11)

这对我有用:

<?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();
?>

打印出来:

wraith:Downloads mwilliamson$ php userfunc_test.php 
    Hello World

答案 2 :(得分:3)

  

新的MyClass;应该返回'Hello World'......

构造函数不返回任何内容。