我的PHP脚本中有一个非常简单的问题。定义了一个函数,该函数采用可变长度参数列表:
function foo() {
// func_get_args() and similar stuff here
}
当我这样称呼它时,它运行得很好:
foo("hello", "world");
但是,我在数组中有我的变量,我需要将它们作为单个参数"单独"传递给函数。例如:
$my_args = array("hello", "world");
foo(do_some_stuff($my_args));
是否有do_some_stuff函数为我拆分参数,以便我可以将它们传递给该函数?
使用
ReflectionFunction::invokeArgs(array $args)
或
call_user_func_array( callback $callback, array $param_arr)
您需要call_user_func_array
call_user_func_array('foo', $my_args);
http://php.net/manual/en/function.call-user-func-array.php
您正在搜索call_user_func_array()
。
http://it2.php.net/manual/en/function.call-user-func-array.php
用法:
$my_args = array("hello", "world");
call_user_func_array('foo', $my_args);
// Equivalent to:
foo("hello", "world");
听起来你在找call_user_func_array
。
http://www.php.net/manual/en/functions.arguments.php#functions.variable-参数列表
这不是你想要的吗?
编辑啊。。。好的…这个怎么样:在PHP 中以参数而非数组的形式传递数组
如果您可以更改foo()
的代码,那么只需在一个地方就可以轻松解决此问题。
function foo()
{
$args = func_get_args();
if(count($args) == 1 && is_array($args[0]))
{
$args = $args[0]
}
// use $args as normal
}
根本不建议使用此解决方案,只是显示了一种可能性:
使用eval
eval ( "foo('" . implode("', '", $args_array) . "' )" );
我知道这是一个老问题,但它仍然是第一个搜索结果,所以这里有一个更简单的方法;
<?php
function add(... $numbers) {
$result=0;
foreach($numbers as $number){
$result+=intval($number);
}
return $result;
}
echo add(...[1, 2])."'n";
$a = [1, 2];
echo add(...$a);
?>
来源:https://www.php.net/manual/en/functions.arguments.php#example-142