你可以将数组内爆到函数参数中吗?

时间:2021-09-12 21:22:55

Is it possible to have an array and pass it into a function as separate arguments?

是否有可能有一个数组并将其作为单独的参数传递给函数?

$name = array('test', 'dog', 'cat');
$name = implode(',' $name);
randomThing($name);

function randomThing($args) {
    $args = func_get_args();
    // Would be 'test', 'dog', 'cat'

    print_r($args);
}

2 个解决方案

#1


11  

No. That's what call_user_func_array() is for.

不,这就是call_user_func_array()的用途。

#2


0  

As of PHP 5.6 you can use ... to pass an array as function arguments. See this example from the PHP documentation:

从PHP 5.6开始,您可以使用...将数组作为函数参数传递。从PHP文档中查看此示例:

function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);

#1


11  

No. That's what call_user_func_array() is for.

不,这就是call_user_func_array()的用途。

#2


0  

As of PHP 5.6 you can use ... to pass an array as function arguments. See this example from the PHP documentation:

从PHP 5.6开始,您可以使用...将数组作为函数参数传递。从PHP文档中查看此示例:

function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);