[英]PHP Function Argument Default Value
大家好。 我有一個processForm函數和一個displayForm函數。 如果缺少表單字段,則processForm函數將返回缺少字段的數組。 在我嘗試將此數組包含到displayForm函數中之前,一切都很好。 這是問題所在:
如果我不這樣做:
displayForm($missingFields=array());
然后我的validateField函數會發出警告,提示它期望參數為數組。 但是,這將覆蓋由processForm函數返回的數組。
我希望我清楚。 謝謝你的幫助。
完整代碼:
if(isset($_POST['action']) && $_POST['action'] = "login")
{
$messages = processForm();
}
processForm()
if($errorMessages)
{
return array("errors" => $errorMessages, "missing" => $missingFields);
}
else
{
$_SESSION['user'] = $user;
header("Location: index.php");
}
form.php的
(!isLoggedIn())? displayForm($messages['errors']=array(),$messages['missing']=array()) : null;
這些是我遇到麻煩的代碼部分。
再次感謝。
您無需在調用中設置默認參數值,而是在簽名中設置它們,例如
function displayForm($arg1 = array()) {
...
}
當你寫
displayForm($消息[ '錯誤'] =陣列())
這實際上是在做這樣的事情
$messages['error'] = array(); // set $messages['error'] to an empty array
displayForm($messages['error']); // pass an empty array to displayForm
這是因為在PHP中,賦值的返回值就是賦值。
您為什么使用此:
displayForm($messages['errors']=array(),$messages['missing']=array())
當您編寫“ $ messages ['errors'] = array()”時 ,這會將$ messeges設置為空白數組。 因此參數為空。 您可以這樣寫:
displayForm($messages['errors'],$messages['missing'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.