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

2021-12-29 00:00:00 function parameters php

可能的重复:
有什么方法可以在 PHP 中指定可选参数值?

偶然发现了这个.

如果我有这样的功能:

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

//do something random

}

调用该函数时,是否可以忽略前两个字段并将它们保留为默认值,但指定第三个字段.

When calling the function is it possible to ignore the first two fields and leave them default yet specify the 3rd.

例如:

$random = $this->my_model->getSomething(USE_DEFAULT, USE_DEFAULT, 10);

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

I know I can pass the 1st and 2nd parameters but all im asking is if their is some kind of special keyword that just says use the default value.

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

Hope that makes sense. its not a problem, just curious.

感谢阅读

推荐答案

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

You need to do that yourself. You can use null to indicate that a default value should be used:

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

    // do something random
}

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

Then pass null when calling it to indicate that you want to use the defaults:

$random = $this->my_model->getSomething(null, null, 10);

<小时>

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


Another possible solution that I use sometimes is an additional parameter at the very end of the parameter list, containing all optional parameters:

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

    // do stuff
}

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

That way you do not need to specify all optional arguments. array_merge() ensures that you are always dealing with a complete set of options. You would use it like this:

$random = $this->my_model->foo(array('limit' => 10));

在这种特殊情况下似乎没有必需的参数,但如果您需要一个,只需将其添加到可选参数的前面即可:

It seems like there is no required parameter this particular case, but if you need one, simply add it in front of the optional ones:

public function foo($someRequiredParameter, $someOtherRequiredParameter, $options = array()) {
    // ...
}

相关文章