25

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

尝试解决方案:

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


}
4

3 回答 3

54

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

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

文档:... PHP 5.6+

于 2014-11-21T14:35:52.940 回答
19

您在这里有几个选择。

首先是使用可选参数。

  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] **/
 }
于 2013-05-29T21:00:14.360 回答
4

您可以在函数声明中不指定参数,然后使用 PHP 的func_get_argfunc_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.
}
于 2013-05-29T20:59:48.310 回答