有没有办法动态调用PHP的同一个类中的方法?我没有正确的语法,但我希望做类似的事情:
$this->{$methodName}($arg1, $arg2, $arg3);
Run Code Online (Sandbox Code Playgroud)
小智 160
有多种方法可以做到这一点:
$this->{$methodName}($arg1, $arg2, $arg3);
$this->$methodName($arg1, $arg2, $arg3);
call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));
Run Code Online (Sandbox Code Playgroud)
您甚至可以使用反射API http://php.net/manual/en/class.reflection.php
Kon*_*lph 10
只需省略大括号:
$this->$methodName($arg1, $arg2, $arg3);
Run Code Online (Sandbox Code Playgroud)
小智 10
您可以使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58467 次 |
| 最近记录: |