PHP中的动态类方法调用
有没有一种方法可以在PHP的同一个类中动态调用方法?我没有正确的语法,但我希望做类似的事情:PHP中的动态类方法调用,php,Php,有没有一种方法可以在PHP的同一个类中动态调用方法?我没有正确的语法,但我希望做类似的事情: $this->{$methodName}($arg1, $arg2, $arg3); 只需省略大括号: $this->$methodName($arg1, $arg2, $arg3); 实现这一点的方法不止一种: $this->{$methodName}($arg1, $arg2, $arg3); $this->$methodName($arg1, $arg2, $arg3)
$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您也可以使用
call\u user\u func()
和call\u user\u func\u array()
如果您在PHP中的类中工作,那么我建议您在PHP5中使用重载的调用函数。你可以找到参考资料
基本上,调用对动态函数的作用与设置和获取对oophp5中变量的作用相同。在我的例子中
$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"
编辑:我已经编辑了代码,现在它与PHP5.3兼容。再举一个例子,这么多年后仍然有效!如果$methodName是用户定义的内容,请确保修剪它。直到我注意到$this->$methodName有一个前导空格,我才让它工作。您可以在PHP中使用重载:
我想也许我的语法是对的,所以我的代码有其他问题,因为它不能正常运行。嗯……有一句话要提醒疲惫的人,如果你的方法在对象上被调用并用PHPUnit测试,
call\u user\u func\u array
就是你的。你我的朋友,刚刚救了我一天!我正在调用call\u user\u func\u数组($this->$name,…)
,不知道为什么它不起作用!谢谢,这是我的工作$此->$methodName($arg1、$arg2、$arg3);这是最初的问题吗?我正在寻找动态调用一个方法,我发现了这个问题。It@Luc-这是最初的问题。事实证明,当我询问时,我的语法是正确的,但我的代码中有其他错误,因此它不起作用。我不确定,但要小心安全问题如果它是用户定义的内容,请确保您所做的不仅仅是修剪名称!比如。。。安全检查!;)在互联网上的某个地方,我详细介绍了如何将用户输入的utf8转换为windows安全字符。QuickBooks让我经历了这个过程——为什么QB不再是我完成销售的一部分……你真的允许客户指定一个输入,动态调用一些方法吗?!我没有进行任何文字验证并检查该类是否确实包含这样一个命名方法。有许多方法可以检查该值。它胜过冗长的switch语句。
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