【问题标题】:Turn array into independent function arguments - howto?将数组转换为独立的函数参数 - 如何?
【发布时间】:2010-11-30 20:11:33
【问题描述】:

我想在函数调用中使用数组中的值作为独立参数。示例:

// Values "a" and "b"
$arr = array("alpha", "beta");
// ... are to be inserted as $a and $b.
my_func($a, $b)
function my_func($a,$b=NULL) { echo "{$a} - {$b}"; }

数组中值的个数未知。

可能的解决方案:

  1. 我可以将数组作为单个参数传递 - 但更愿意作为多个独立的函数参数传递。

  2. implode() 将数组转换为逗号分隔的字符串。 (失败,因为它只是一个字符串。)

  3. 使用单个参数:

    $str = "'a','b'";
    function goat($str);  // $str needs to be parsed as two independent values/variables.
    
  4. 使用eval()?

  5. 遍历数组?

欢迎提出建议。谢谢。

【问题讨论】:

  • "数组中值的个数未知。" -- 它们是否至少与函数签名的 arg 列表相匹配?

标签: php arrays function


【解决方案1】:

这个问题已经相当老了,但在 PHP 5.6+ 中终于有了更直接的支持:

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list.new

$arr = array("alpha", "beta");
my_func(...$arr);

【讨论】:

    【解决方案2】:

    如果我理解正确的话:

    $arr = array("alpha", "beta");
    call_user_func_array('my_func', $arr);
    

    【讨论】:

      【解决方案3】:

      尝试列表()

      // Values "a" and "b"
      $arr = array("alpha", "beta");
      list($a, $b) = $arr;
      my_func($a, $b);
      
      function my_func($a,$b=NULL) { echo "{$a} - {$b}"; }
      

      【讨论】:

      • 技术上正确(call_user_func_array 是你应该如何做这种类型的行为,但这是非常聪明的。+1
      • 好建议。然后,您可以使用标准函数调用(没有 call_user_func_array)来保持代码干净。唯一的缺陷是 list 要求您对参数进行硬编码 ... list($a, $b) ... 而我没有预先确定数组值的数量。
      • 我在查找这个问题时正在考虑list(),但它不允许无限量的参数,是吗?
      • 数组元素个数未知,所以不是万能的解决方案。
      【解决方案4】:

      您可以使用call_user_func_array() 做到这一点。它可以创造奇迹(甚至从 PHP 5.3 开始使用 lambda 函数)。

      【讨论】:

        猜你喜欢
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-08
        • 1970-01-01
        • 2013-02-04
        • 2011-01-11
        • 1970-01-01
        相关资源
        最近更新 更多