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;
}
}如何以其他方式调用方法。我不想使用开关,因为当我添加新方法时,我也必须添加它来切换。我想避免那样做。
问:如何从类中动态调用方法?
我的想法:
if(!function_exists($method)){
$result = 'function not exist!';
}
else {
$result = call_user_func_array($method, $params);
} 发布于 2014-05-23 13:37:36
嗯,你可以这样做,
function index($method, $params) {
if (!method_exists($this, $method)) {
$result = 'method does not exist!';
} else {
$result = call_user_func_array(array($this, $method), $params);
}
}
return $result;
}发布于 2014-05-23 13:37:17
嗯我错了..。
您应该将开关替换为:
call_user_func_array(array($this, $method), $params);https://stackoverflow.com/questions/23830453
复制相似问题