我有一个这样工作的程序:$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]);
1 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
您可以使用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
希望有帮助
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消