有没有一种方法可以在PHP中动态调用同一个类中的方法?我不确定语法是否正确,但我想做类似于这样的事情:
$this->{$methodName}($arg1, $arg2, $arg3);
$this->{$methodName}($arg1, $arg2, $arg3);
有不止一种方法来做到这点:
$this->{$methodName}($arg1, $arg2, $arg3);
$this->$methodName($arg1, $arg2, $arg3);
call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));
你甚至可以使用反射API http://php.net/manual/en/class.reflection.php
call_user_func_array
是你需要的。 - OK surecall_user_func_array($this->$name, ...)
,不知道为什么它不起作用! - Pubudu Dodangoda您可以在PHP中使用重载:重载
class Test {
private $name;
public function __call($name, $arguments) {
echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);
//do a get
if (preg_match('/^get_(.+)/', $name, $matches)) {
$var_name = $matches[1];
return $this->$var_name ? $this->$var_name : $arguments[0];
}
//do a set
if (preg_match('/^set_(.+)/', $name, $matches)) {
$var_name = $matches[1];
$this->$var_name = $arguments[0];
}
}
}
$obj = new Test();
$obj->set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String
echo $obj->get_name();//Echo:Method Name: get_name Arguments:
//return: Any String
只需省略大括号:
$this->$methodName($arg1, $arg2, $arg3);
您还可以使用call_user_func()
和call_user_func_array()
class test{
function echo_this($text){
echo $text;
}
function get_method($method){
$object = $this;
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
}
$test = new test();
$echo = $test->get_method('echo_this');
$echo('Hello'); //Output is "Hello"
编辑:我已经编辑了代码,现在它与PHP 5.3兼容。另一个示例在这里
就我的情况而言。
$response = $client->{$this->requestFunc}($this->requestMsg);
$methodName
是用户定义的内容,则删除其中的空格。我之前无法让 $this->$methodName
正常工作,直到我注意到它有一个前导空格。