【问题标题】:PHP: Convert array argument as an individual argument for another functionPHP:将数组参数转换为另一个函数的单个参数
【发布时间】:2016-01-23 17:08:29
【问题描述】:

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

$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,从第二个参数到基于数组项的无穷大

【问题讨论】:

  • 那么你的问题是什么?
  • @JohnConde 如何转换我的函数数组项并将每个项应用于call_another_function,从第二个参数到基于数组项的无穷大
  • php 内置函数call_user_func_array 怎么样? php.net/manual/de/function.call-user-func-array.php
  • call_another_funciton` 已经在使用它来获取所有函数参数。这里第一个参数已使用array_slice 在该函数中切片
  • @CodeLover call_user_func_array 以数组形式调用一个函数。我会根据你的代码给你一个例子。

标签: php arrays arguments


【解决方案1】:

评论中提到,可以使用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"
}

【讨论】:

    【解决方案2】:

    我认为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);
    

    【讨论】:

    • 感谢您的代码,但我无法理解它。 call_another_function() has $funcargs=func_get_args();` 在里面。
    猜你喜欢
    • 2023-04-08
    • 2023-03-17
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2017-08-07
    相关资源
    最近更新 更多