有没有办法为PHP动态调用同一个类中的方法?我没有正确的语法,但我希望做一些类似的事情:
$this->{$methodName}($arg1, $arg2, $arg3);发布于 2008-10-30 19:50:55
有不止一种方法可以做到这一点:
$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
发布于 2008-10-30 19:46:35
只需省略大括号:
$this->$methodName($arg1, $arg2, $arg3);发布于 2017-01-07 05:11:35
您可以在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 Stringhttps://stackoverflow.com/questions/251485
复制相似问题