【问题标题】:passing multiple arguments to function php将多个参数传递给函数php
【发布时间】:2013-05-29 20:54:47
【问题描述】:

为新手问题道歉,但我有一个函数,它接受两个参数,一个是数组,一个是变量function createList($array, $var) {}。我有另一个函数,它只使用一个参数调用 createList,$var, doSomething($var); 它不包含数组的本地副本。如何将一个参数传递给 PHP 中需要两个参数的函数?

尝试解决方案:

function createList (array $args = array()) {
    //how do i define the array without iterating through it?
 $args += $array; 
 $args += $var;


}

【问题讨论】:

    标签: php function


    【解决方案1】:

    这里有几个选项。

    首先是使用可选参数。

      function myFunction($needThis, $needThisToo, $optional=null) {
        /** do something cool **/
      }
    

    另一种方法是避免命名任何参数(这种方法不是首选,因为编辑器无法提示任何内容,并且方法签名中没有文档)。

     function myFunction() {
          $args = func_get_args();
    
          /** now you can access these as $args[0], $args[1] **/
     }
    

    【讨论】:

    • 真棒不知道你可以设置一个参数为空谢谢!
    【解决方案2】:

    如果您可以使用 PHP 5.6+,则有一种用于变量参数的新语法:省略号关键字。
    它只是将所有参数转换为一个数组。

    function sum(...$numbers) {
        $acc = 0;
        foreach ($numbers as $n) {
            $acc += $n;
        }
        return $acc;
    }
    echo sum(1, 2, 3, 4);
    

    文档:... in PHP 5.6+

    【讨论】:

    【解决方案3】:

    您可以在函数声明中不指定参数,然后使用 PHP 的 func_get_arg 或 func_get_args 获取参数。

    function createList() {
       $arg1 = func_get_arg(0);
       //Do some type checking to see which argument it is.
       //check if there is another argument with func_num_args.
       //Do something with the second arg.
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2014-12-19
      相关资源
      最近更新 更多