【问题标题】:How to handle undetermined number of arguments?如何处理不确定数量的参数?
【发布时间】:2020-09-02 17:24:47
【问题描述】:

我有一个这样的程序:

$e = "name,Alan,Georges,Edith,Julia,Donna,Bernard,Christophe,Salvatore,Laure,Thomas";
$f = explode("," ,$e);
if (function_exists($f[0])) {
$f[0]($f[1], $f[2], $f[3], $f[4], $f[5], $f[6], $f[7], $f[8], $f[9], $f[10]);
}

我可以更优雅地处理这个吗? 我的意思是,我可以不写就处理例如 30 个参数吗:

$f[0]($f[1], $f[2], $f[3], ..., ..., $f[26], $f[27], $f[28], $f[29], $f[30]);

【问题讨论】:

    标签: php arguments parameter-passing


    【解决方案1】:

    您可以使用call_user_func_array()通过数组传递参数:

    $f = ['foo', 'param1', 'param2'];
    $func = array_shift($f); // remove function name.
    call_user_func_array($func, $f);
    

    (使用上面的示例代码和下面的函数......)

    要获取函数参数的任意列表,请使用func_get_args()

    function foo() {
        $args = func_get_args();
        print_r($args);
    }
    

    您甚至不必指定参数,只需传递任意数量的参数即可:

    foo(1, 2, 4, 'hello', 1.234, ['foo', 'bar']);
    

    产生输出

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 4
        [3] => hello
        [4] => 1.234
        [5] => Array
            (
                [0] => foo
                [1] => bar
            )
    
    )
    

    https://www.php.net/manual/en/function.func-get-args

    https://www.php.net/manual/en/function.call-user-func-array

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      相关资源
      最近更新 更多