我试图用来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)
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)