【发布时间】:2014-07-12 21:15:18
【问题描述】:
class Test {
function index($method, $params) {
if (!method_exists($this, $method)) {
$result = 'method does not exist!';
}
else {
switch ($method) {
case 'add':
$result = $this->add($params[0], $params[1], $params[2]);
break;
case 'sub':
$result = $this->sub($params[0], $params[1]);
break;
default:
$result = 'no method selected!';
break;
}
}
return $result;
}
public function add($n1, $n2, $n3) {
return $n1 + $n2;
}
public function sub($n1, $n2) {
return $n1 - $n2;
}
}
如何以其他方式调用方法。我不想使用 switch,因为当我添加新方法时,我也必须将它添加到 switch。我想避免这种情况。
问:如何动态调用类中的方法?
我的想法:
if(!function_exists($method)){
$result = 'function not exist!';
}
else {
$result = call_user_func_array($method, $params);
}
【问题讨论】:
-
$result = call_user_func_array(array('Test', $method), $params);- 有关回调的详细信息,请参阅 the docs