我对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 image(array $img)
{
    $defaults = array(
        'src'    => 'cow.png',
        'alt'    => 'milk factory',
        'height' => 100,
        'width'  => 50
    );

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

其他回答

<?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

?>

另一种写法是:

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)

你也可以检查你是否有一个空字符串作为参数,这样你可以调用:

Foo ('blah', "", '非默认y值',null);

函数下面:

function foo($blah, $x = null, $y = null, $z = null) {
    if (null === $x || "" === $x) {
        $x = "some value";
    }

    if (null === $y || "" === $y) {
        $y = "some other value";
    }

    if (null === $z || "" === $z) {
        $z = "some other value";
    }

    code here!

}

不管你填的是null还是"",你仍然会得到相同的结果。

在PHP 8中,我们可以使用命名参数来解决这个问题。

所以我们可以解决这个问题的原始海报所描述的问题:

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

:

foo(blah: "blah", y: "test");

参考:https://wiki.php.net/rfc/named_params(特别是“跳过默认值”部分)

这种情况下,当对象更好-因为你可以设置你的对象来保存x和y,设置默认值等。

使用数组的方法接近于创建对象(事实上,对象是一组参数和函数,它们将在对象上工作,函数接受数组将在一些ov参数上工作)

当然,你总是可以用一些技巧来设置null或类似的默认值