如何在需要默认值时跳过参数

Ale*_*x S 7 php

如果我有这样的功能:

function abc($a,$b,$c = 'foo',$d = 'bar') { ... }
Run Code Online (Sandbox Code Playgroud)

我想$c假设它是默认值,但需要设置$d,我将如何在PHP中进行调用?

Sas*_*gov 10

不幸的是,PHP无法做到这一点.你可以通过检查null来解决这个问题.例如:

function abc($a, $b, $c = 'foo', $d = 'bar') {
    if ($c === null)
        $c = 'foo';
    // Do something...
}
Run Code Online (Sandbox Code Playgroud)

那你就像这样调用函数:

abc('a', 'b', null, 'd');
Run Code Online (Sandbox Code Playgroud)

不,它不是很漂亮,但它确实起作用了.如果你真的喜欢冒险,你可以传入一个关联数组而不是最后两个参数,但我认为这比你想要的更多.