我有一個函數需要大約10個參數,其中大多數是可選的。我想知道如果我能夠以這樣的方式實現它,該函數的用戶不需要打擾參數的順序。 例如:允許PHP中的任何順序的多個參數
public function foo($arg1, $arg2, $arg3='',$arg4='', $arg5='', $arg6='', $arg7=''){}
現在,當我使用這個功能,我可以簡單地
$this->foo($arg1val, $arg2val, $arg6val);
是否有一個PHP的方式做到這一點?
下面是我如何實現這一點: 我已經列出了函數在API中接受的參數,因此用戶可以按照鍵=>值對的數組中的任何順序傳遞參數。
例如:
public function argumentsFilter($origParams, $newParams){
$tmpArr = array();
foreach ($origParams as $origKey){
foreach($newParams as $newKey => $newVal){
if($newKey == $origKey){
$tmpArr[$origKey] = $newVal;
}
}
if(empty($tmpArr[$origKey])){
$tmpArr[$origKey] = '';
}
}
return $tmpArr;
}
public function foo($arg1, $arg2, $arg=array()){
$validArgList = array('arg3', 'arg4', 'arg5', 'arg6', 'arg7');
$correctedArgList = $this->argumentsFilter($validArgList, $arg);
}
有沒有更優雅的方式來做到這一點?
您可以嘗試使用[技巧](http://blog.perplexedlabs.com/2009/04/22/php-named-parameters/),但傳遞數組的IMO是最簡單的方法。 如果您希望像其他語言(如:Python,C#)一樣支持命名的[參數](http://en.wikipedia.org/wiki/Named_parameter),它可能不會很快](https://bugs.php.net/bug.php?id=22216) – NullUserException