PHP函数 - 忽略一些默认参数

fl3*_*3x7 7 php parameters function

可能重复:
在PHP中指定可选参数值的任何方法?

随便碰到了这个.

如果我有这样的功能:

public function getSomething($orderBy='x', $direction = 'DESC', $limit=null){

//do something random

}
Run Code Online (Sandbox Code Playgroud)

调用函数时,可以忽略前两个字段并保留默认值但指定第3个字段.

例如:

$random = $this->my_model->getSomething(USE_DEFAULT, USE_DEFAULT, 10);
Run Code Online (Sandbox Code Playgroud)

我知道我可以传递第一个和第二个参数,但我要问的是,它们是否是某种特殊的关键字,只是说使用默认值.

希望有道理.这不是问题,只是好奇.

谢谢阅读

jwu*_*ler 12

你需要自己做.您可以使用它null来指示应使用默认值:

public function getSomething($orderBy = null, $direction = null, $limit = null) {
    // fallbacks
    if ($orderBy === null) $orderBy = 'x';
    if ($direction === null) $direction = 'DESC';

    // do something random
}
Run Code Online (Sandbox Code Playgroud)

然后null在调用它时传递以指示您要使用默认值:

$random = $this->my_model->getSomething(null, null, 10);
Run Code Online (Sandbox Code Playgroud)

我有时使用的另一种可能的解决方案是参数列表最后的附加参数,包含所有可选参数:

public function foo($options = array()) {
    // merge with defaults
    $options = array_merge(array(
        'orderBy'   => 'x',
        'direction' => 'DESC',
        'limit'     => null
    ), $options);

    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

这样您就不需要指定所有可选参数.array_merge()确保您始终处理一整套选项.你会像这样使用它:

$random = $this->my_model->foo(array('limit' => 10));
Run Code Online (Sandbox Code Playgroud)

似乎这个特殊情况没有必需的参数,但是如果你需要参数,只需将它添加到可选的前面:

public function foo($someRequiredParameter, $someOtherRequiredParameter, $options = array()) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)