是否可以跳过php(5)函数调用中具有默认值的参数?

spr*_*man 7 php

我有这个:

function foo($a='apple', $b='brown', $c='Capulet') {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

这样的事情是可能的:

foo('aardvark', <use the default, please>, 'Montague');
Run Code Online (Sandbox Code Playgroud)

Gum*_*mbo 12

如果它是您的函数,您可以使用null通配符并稍后在函数内设置默认值:

function foo($a=null, $b=null, $c=null) {
    if (is_null($a)) {
        $a = 'apple';
    }
    if (is_null($b)) {
        $b = 'brown';
    }
    if (is_null($c)) {
        $c = 'Capulet';
    }
    echo "$a, $b, $c";
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用null以下方法跳过它们:

foo('aardvark', null, 'Montague');
// output: "aarkvark, brown, Montague"
Run Code Online (Sandbox Code Playgroud)


cee*_*yoz 5

如果它是你自己的函数而不是PHP的核心,你可以这样做:

function foo($arguments = []) {
  $defaults = [
    'an_argument' => 'a value',
    'another_argument' => 'another value',
    'third_argument' => 'yet another value!',
  ];

  $arguments = array_merge($defaults, $arguments);

  // now, do stuff!
}

foo(['another_argument' => 'not the default value!']);
Run Code Online (Sandbox Code Playgroud)


spr*_*man 4

发现了这个,这可能仍然是正确的:

http://www.webmasterworld.com/php/3758313.htm

简短的回答:不。

长答案:是的,以上面概述的各种笨拙的方式。