我有一个类,其中的方法采用不同数量的参数。我得到了一个包含方法的数组,也包含不同数量的参数。
我需要使用适当数量的参数来调用方法才能使其正常工作。如果数组中的键没有值,则应始终将 $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);
关于php - 检查数组关键参数并使用适当数量的参数调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23498593/