回答
还有就是要做到这一点不止一种方法:
$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
我想也许我确实拥有正确的语法,所以我的代码有其他问题,因为它的功能不正常。嗯... – VirtuosiMedia 2008-10-30 20:00:52
只要省略括号:
$this->$methodName($arg1, $arg2, $arg3);
谢谢。我曾经想过,但还没有尝试过。 – VirtuosiMedia 2008-10-30 19:51:37
您还可以使用call_user_func()
和call_user_func_array()
如果你在PHP的一个类中工作,那么我会建议在PHP5中使用重载的__call函数。你可以找到参考here。
基本上__call为动态函数做什么__set和__get为PHP OO中的变量做了什么。
在我的情况。
$response = $client->{$this->requestFunc}($this->requestMsg);
使用PHP SOAP。
我不知道但要小心安全问题 – tom10271 2016-02-02 01:39:15
可以在单个变量使用封闭储存方法:
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兼容。另一个例子here
这些年后仍然有效!确保您修剪$ methodName,如果它是用户定义的内容。我无法获得$ this - > $ methodName的工作,直到我发现它有一个领先的空间。
可以使用重载在PHP中: Overloading
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
- 1. 动态调用PHP类方法
- 2. 动态调用类方法
- 3. 如何动态调用PHP中的类方法?
- 4. 调用JUNIT类的动态方法
- 5. 如何在PHP 5中动态调用子类方法?
- 6. PHP中的动态静态方法调用?
- 7. 当在PHP中调用任何类的方法时自动调用方法
- 8. 动态执行std类的方法php
- 9. 调用静态类方法
- 10. PHP调用类的静态方法的类名
- 11. 从非静态类动态调用非静态方法的最简单方法?
- 12. 动态调用DLL中的方法
- 13. PHP OOP - 从类内的另一个类调用静态方法
- 14. 动态方法调用
- 15. 从调用的方法在父类中派生的静态方法在PHP
- 16. 如何动态调用PHP中的方法?
- 17. 从静态基类方法调用静态派生类方法
- 18. 如何在.NET中动态调用类的方法?
- 19. 从视觉c中的另一个类调用动态方法#
- 20. Objective-C中动态类的调用方法?
- 21. PHP - 获取类,其中调用方法
- 22. 动态方法在define_method中调用
- 23. 在VB.Net中动态调用方法
- 24. 调用非静态方法动态
- 25. 调用一类的非静态方法
- 26. 调用静态方法的一类
- 27. 调用其他类的静态方法
- 28. 如何调用类的静态方法?
- 29. PHP中类的静态方法/函数
- 30. 从相同的类属性语法中调用类方法? PHP
是它原来的问题?我正在寻找动态调用方法,我发现这个问题。它的语法与andy.gurin给出的语法相同,我没有看到显示问题更新的链接。无论如何...感谢有问题和感谢的贡献者:-) – 2009-07-30 01:43:47
@Luc - 这是原来的问题。事实证明,当我问我的时候我的语法正确,但是我的代码有其他问题,所以它不起作用。 – VirtuosiMedia 2009-07-30 08:09:03