你需要自己完成这个操作。你可以使用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()) {
$options = array_merge(array(
'orderBy' => 'x',
'direction' => 'DESC',
'limit' => null
), $options);
}
这样,您就无需指定所有可选参数了。 array_merge()
确保您始终处理完整的选项集。您可以像这样使用它:
$random = $this->my_model->foo(array('limit' => 10));
看起来在这种情况下没有必填参数,但如果需要一个,请将其添加到可选参数之前:
public function foo($someRequiredParameter, $someOtherRequiredParameter, $options = array()) {
// ...
}