2012-03-02 141 views
6

可能重复:
Any way to specify optional parameter values in PHP?PHP函数 - 忽略某些默认参数

只是随机跨越这来了。

如果我有一个函数,像这样:

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

//do something random 

} 

当调用该函数是可以忽略前两个字段,让他们默认尚未指定第三位。

例如:

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

我知道我可以通过第一和第二参数,但所有IM问的是,如果他们是某种特殊的关键字,那只是说使用默认值。

希望是有道理的。它不是一个问题,只是好奇。

感谢您的阅读

+0

感谢大家的输入:) – fl3x7 2012-03-02 23:53:40

+0

当调用函数或类的方法时,可以使用Syntactic来忽略默认参数https://github.com/topclaudy/php-syntactic – cjdaniel 2016-06-19 18:30:00

回答

11

你需要做的是自己。您可以使用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()) { 
    // ... 
} 
+0

Syntactic为此提供了一个很好的方法。在这里检查https://github.com/topclaudy/php-syntactic – cjdaniel 2016-06-19 18:31:10

-2

您不能忽略params。但是你可以做这样的事情:

public function getSomething($limit=null){ 

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

} 


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

... 

} 

再见

+2

不,他不能。 PHP不支持重载。 – jwueller 2012-03-02 23:29:42

1

说实话,当函数试图做得太多时,这成为一个问题。当你看到一个函数增长到超过几个参数时(通常是继承旧代码的穷人,并且附加参数是“完成工作”的最快方法),几乎总是有一个更好的设计模式。

难以捉摸的答案是根据你的问题最好的,但看看圈复杂度: http://en.wikipedia.org/wiki/Cyclomatic_complexity

这是要知道,如果你的函数是做太多的好办法,这使得你的问题更小的问题比现在可能要多。

+0

没错。每个人都应该记住复杂性。 +1! – jwueller 2012-03-02 23:46:28

+0

谢谢。将读入它:) – fl3x7 2012-03-02 23:54:24