如何处理不确定数量的参数?

问题描述 投票:0回答:1

我有一个像这样的程序:

$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个回答
0
投票

您可以使用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

希望有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.