PHP:将数组参数转换为另一个函数的单独参数


PHP: Convert array argument as an individual argument for another function

我想在我的函数中使用数组作为参数,然后转换/提取该数组,并在第一个参数之后将每个元素应用到另一个函数的参数中。

$args = [ $arg1, $arg2, ...];
function foo($one = 'string', $two='string', array $args = [])
{
    // my stuffs
    //here calling another function where need to pass arguments
    // the first argument is required
    // from second argument I want to apply array item individually.
    // So this function has func_get_args()
    call_another_function($one, $arg1, $arg2, ...);
}

那么我如何转换我的函数数组项并将每个项应用于call_another_function从第二个参数到无限基于数组项

正如评论中提到的,您可以使用call_user_func_array来调用call_another_function函数:

<?php
$args = [ $arg1, $arg2, ...];
function foo($one = 'string', $two='string', array $args = [])
{
    // your stuffs
    // Put the first argument to the beginning of $args
    array_unshift($args, $one);
    // Call another function with the new arguments
    call_user_func_array('call_another_function', $args);
}
function call_another_function(){
    var_dump(func_get_args());
}
foo('one', 'two', $args);

将输出如下内容:

array(3) {
  [0] =>
  string(3) "one"
  [1] =>
  string(4) "arg1"
  [2] =>
  string(4) "arg2"
}

我认为call_another_function应该有这样的签名:

function call_another_function($one, $argumentsArray)

第二个形参是一个数组,你可以给它添加任意数量的实参。

$argumentArray = array();
array_push($argumentArray, "value1");
array_push($argumentArray, "value2");
array_push($argumentArray, "value3");
...
call_another_function($one, $argumentArray);