php - 检查数组关键参数并使用适当数量的参数调用方法

标签 php arrays foreach

我有一个类,其中的方法采用不同数量的参数。我得到了一个包含方法的数组,也包含不同数量的参数。

我需要使用适当数量的参数来调用方法才能使其正常工作。如果数组中的键没有值,则应始终将 $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/

相关文章:

php - 如何通过publish_post钩子(Hook)获取在wordpress上发布的帖子数据?

java - 另一个 "Can only iterate over an array or an instance of java.lang.Iterable"问题

python - 在 Numpy 数组子类中更改 `__getitem__` 和 `__setitem__` 的行为

java - 简单的校验和算法

php - 在 ArrayObject 中循环和取消设置时 foreach 出现意外行为。一个项目被忽略

PHP foreach 循环输出到一个新数组

php - mod_fcgid 从管道读取超时、 header 之前的脚本输出结束、PHP 的多个版本

php - 使用短标签从命令行运行 php

php - 验证值有两种可能的类型

c - 有一个结构变量代表标签