有没有一种方法可以在PHP的同一类中动态调用方法?我没有正确的语法,但我正在寻找类似的方法:
$this->{$methodName}($arg1, $arg2, $arg3);
有没有一种方法可以在PHP的同一类中动态调用方法?我没有正确的语法,但我正在寻找类似的方法:
$this->{$methodName}($arg1, $arg2, $arg3);
Answers:
有多种方法可以做到这一点:
$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。
call_user_func_array($this->$name, ...),想知道为什么它不起作用!
您可以在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
如果您正在PHP中使用类,那么我建议您在PHP5中使用重载的__call函数。您可以在此处找到参考。
基本上,__call对动态函数起作用,而__set和__get对OO PHP5中的变量起作用。
这些年来仍然有效!如果是用户定义的内容,请确保修剪$ methodName。我无法使$ this-> $ methodName起作用,直到我注意到它有一个前导空间。
就我而言。
$response = $client->{$this->requestFunc}($this->requestMsg);
使用PHP SOAP。
您可以使用闭包将方法存储在单个变量中:
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兼容。这里的另一个例子