我有一个类,它的方法采用不同数量的参数。我得到了一个方法数组,也有不同数量的参数
我需要调用具有适当数量的参数的方法来工作。如果数组中的键没有值,则应该始终将$input
作为第一个参数传递。
$arr = ['trim', 'between' => [6, 254]];
我的尝试失败
foreach ($arr as $method) {
if (count($method) === 0) {
$this->$method($input);
} elseif (count($method) === 1) {
$this->$method($input, $method[0]);
} elseif (count($method) === 2) {
$this->$method($input, $method[0], $method[1]);
}
}
误差Fatal error: Method name must be a string in (..) on line N
private function trim($input) //1 param
{
$this->input = trim($input);
}
private function max($input, $max) //2 params
{
if (!(strlen($input) <= $max)) {
$this->errors[] = __FUNCTION__;
}
}
private function between($input, $min, $max) //3 param
{
if (!(strlen($input) > $min && strlen($this->input) < $max)) {
$this->errors[] = __FUNCTION__;
}
}
您可以轻松地使用call_user_func_array
动态调用您想要的任何方法,并使用可变数量的参数。只是有些细节需要处理。
首先,$arr
的格式方便但不一致。有时方法名是值(例如trim
),有时是键(例如between
)。你需要规范化的东西:
foreach ($arr as $key => $value) {
if (is_int($key)) { // $key => 'trim'
$method = $value;
$arguments = [$input];
}
else { // 'trim' => [...]
$method = $key;
$arguments = array_merge([$input], is_array($value) ? $value : [$value]);
}
现在您已经有了$method
和$arguments
,最后一步很简单:
call_user_func_array([$this, $method], $arguments);
来理解错误$arr = [0 => 'trim', 'between' => [6,254]];
你迭代值所以在$method中你得到1)'trim', 2) [6254] (not 'between')