我对PHP函数的默认值感到困惑。假设我有一个这样的函数:

function foo($blah, $x = "some value", $y = "some other value") {
    // code here!
}

如果我想使用$x的默认参数,并为$y设置一个不同的参数呢?

我一直在尝试不同的方法,但我越来越困惑了。例如,我尝试了以下两种:

foo("blah", null, "test");
foo("blah", "", "test");

但这两种方法都不会为$x提供合适的默认参数。我还尝试通过变量名来设置它。

foo("blah", $x, $y = "test");   

我满心期待这样的东西能起作用。但它完全不像我想象的那样。似乎无论我做什么,每次调用函数时,我都必须输入默认参数。我肯定遗漏了一些明显的东西。


当前回答

另一种写法是:

function sum($args){
    $a = $args['a'] ?? 1;
    $b = $args['b'] ?? 1;
    return $a + $b;
}

echo sum(['a' => 2, 'b' => 3]); // 5 
echo sum(['a' => 2]); // 3 (2+1)
echo sum(['b' => 3]); // 4 (1+3)
echo sum([]); // 2 (1+1)

其他回答

向函数传递一个数组,而不是单个参数,并使用空合并运算符(PHP 7+)。

下面,我将传递一个包含2项的数组。在函数内部,我检查item1的值是否已设置,如果没有分配默认vault。

$args = ['item2' => 'item2',
        'item3' => 'value3'];

    function function_name ($args) {
        isset($args['item1']) ? $args['item1'] : 'default value';
    }

PHP 8的方法:

function foo($blah, ?$x, ?$y) {
    $x = $x ?? "some value";
    $y = $y ?? "some other value";
}
function image(array $img)
{
    $defaults = array(
        'src'    => 'cow.png',
        'alt'    => 'milk factory',
        'height' => 100,
        'width'  => 50
    );

    $img = array_merge($defaults, $img);
    /* ... */
}

我的2美分与空合并运算符??(从PHP 7开始)

function foo($blah, $x = null, $y = null) {
    $varX = $x ?? 'Default value X';
    $varY = $y ?? 'Default value Y';
    // ...
}

你可以在我的replyit上查看更多的例子

<?php
function info($name="George",$age=18) {
echo "$name is $age years old.<br>";
}
info();     // prints default values(number of values = 2)
info("Nick");   // changes first default argument from George to Nick
info("Mark",17);    // changes both default arguments' values

?>