将数组作为参数列表传递给函数[duplicate]

时间:2021-09-25 16:50:12

This question already has an answer here:

这个问题在这里已有答案:

Google won't help me; I want to pass an array as an argument list to a function.

谷歌不会帮助我;我想将一个数组作为参数列表传递给函数。

I can't edit the function itself, so I can't pass an array. It expects this:

我无法编辑函数本身,所以我无法传递数组。它期望这样:

function doSomething($arg1, $arg2, [$arg3...]) {
    //code...
}

And I have this:

我有这个:

$args = array('arg1', 'arg2', 'arg3'...);

How can I pass them anyway?

我怎么能通过它们呢?

1 个解决方案

#1


1  

You can use call_user_func_array.

您可以使用call_user_func_array。

Use like:

使用如下:

$array = array(1, 2, 3);
call_user_func_array("myfunc", $array);

function myfunc($a, $b, $c) {
    var_dump($a, $b, $c); // 1 2 3
}

$array = array(2, 3);
$first = 1;
call_user_func_array("myfunc", array_merge(arary($first), $array));

function myfunc($a, $b, $c) {
    var_dump($a, $b, $c); // 1 2 3
}

In case of an object instance your callback should look like:

如果是对象实例,您的回调应如下所示:

array($obj, "someFunc")

so:

所以:

call_user_func_array(array($obj, "someFunc"), $array);

#1


1  

You can use call_user_func_array.

您可以使用call_user_func_array。

Use like:

使用如下:

$array = array(1, 2, 3);
call_user_func_array("myfunc", $array);

function myfunc($a, $b, $c) {
    var_dump($a, $b, $c); // 1 2 3
}

$array = array(2, 3);
$first = 1;
call_user_func_array("myfunc", array_merge(arary($first), $array));

function myfunc($a, $b, $c) {
    var_dump($a, $b, $c); // 1 2 3
}

In case of an object instance your callback should look like:

如果是对象实例,您的回调应如下所示:

array($obj, "someFunc")

so:

所以:

call_user_func_array(array($obj, "someFunc"), $array);