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

8

可能是重复问题:
有没有办法在PHP中指定可选参数值?

我刚刚偶然看到这个问题。

如果我有一个函数如下:

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

//do something random

}

调用函数时,是否可以忽略前两个字段并将它们保持默认,同时指定第三个字段。

例如:

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

我知道我可以传递第一和第二个参数,但我想知道是否有一种特殊的关键字可以表示使用默认值。

希望这样说得清楚。这不是问题,只是好奇。

谢谢阅读。


感谢大家的参与和贡献 :) - fl3x7
当调用类的函数或方法时,您可以使用Syntactic来忽略默认参数。https://github.com/topclaudy/php-syntactic - cjdaniel
4个回答

14

你需要自己完成这个操作。你可以使用null来表示应该使用默认值:

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

    // do something random
}

在调用时传入null以表示您想要使用默认值:

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

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

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

    // do stuff
}

这样,您就无需指定所有可选参数了。 array_merge() 确保您始终处理完整的选项集。您可以像这样使用它:

$random = $this->my_model->foo(array('limit' => 10));
看起来在这种情况下没有必填参数,但如果需要一个,请将其添加到可选参数之前:
public function foo($someRequiredParameter, $someOtherRequiredParameter, $options = array()) {
    // ...
}

Syntactic为此提供了一种优雅的方法。在此处检查:https://github.com/topclaudy/php-syntactic - cjdaniel
使用PHP8,可以通过命名参数(https://php.watch/versions/8.0/named-parameters)轻松实现此目标。$random = $this->my_model->getSomething(limit: 10); - Welder Lourenço

2
坦白说,当函数试图做太多事情时,这会成为一个问题。当你看到一个函数的参数超过几个时,通常有更好的设计模式(通常是那些继承旧代码的可怜人,添加参数是最快的“完成任务”的方法)。
Elusive的答案是根据你的问题最好的,但是请查看圈复杂度: http://en.wikipedia.org/wiki/Cyclomatic_complexity 这是一个了解你的函数是否做得太多的好方法,这使得你的问题不太可能是现在的问题。

没错,每个人都应该牢记复杂性。加一! - jwueller
谢谢。我会仔细阅读 :) - fl3x7

0

-2

你不能忽略参数。但是你可以这样做:

public function getSomething($limit=null){

return $this->getSomething('x','DESC',$limit);

}


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

...

}

再见


3
不行,PHP不支持重载。 - jwueller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接