猿问

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

我有一个这样工作的程序:


$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]);


白衣染霜花
浏览 91回答 1
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-argshttps://www.php.net/manual/en/function.call-user-func-array希望有帮助
随时随地看视频慕课网APP
我要回答