简体   繁体   English

PHP函数参数默认值

[英]PHP Function Argument Default Value

Hey all. 大家好。 I have a processForm function and a displayForm function. 我有一个processForm函数和一个displayForm函数。 If there are missing form fields the processForm function returns an array of missing fields. 如果缺少表单字段,则processForm函数将返回缺少字段的数组。 This is all fine and dandy until I try to include this array into the displayForm function. 在我尝试将此数组包含到displayForm函数中之前,一切都很好。 Here's the problem: 这是问题所在:

If I don't do this: 如果我不这样做:

displayForm($missingFields=array());

then my validateField function throws a warning that it is expecting the parameter to be an array. 然后我的validateField函数会发出警告,提示它期望参数为数组。 However, this overwrites the array returned by the processForm function. 但是,这将覆盖由processForm函数返回的数组。

I hope I'm clear. 我希望我清楚。 Thanks for any help. 谢谢你的帮助。

Full Code: 完整代码:

if(isset($_POST['action']) && $_POST['action'] = "login")
{
    $messages = processForm();
}

processForm() processForm()

if($errorMessages)
{
     return array("errors" => $errorMessages, "missing" => $missingFields);
}
else 
{
    $_SESSION['user'] = $user;
    header("Location: index.php");
}

form.php form.php的

(!isLoggedIn())? displayForm($messages['errors']=array(),$messages['missing']=array()) : null;

These are the sections of the code I'm having trouble with. 这些是我遇到麻烦的代码部分。

Thanks again. 再次感谢。

You don't set default argument values in the call, you set them in the signature, for example 您无需在调用中设置默认参数值,而是在签名中设置它们,例如

function displayForm($arg1 = array()) {
    ...
}

When you write 当你写

displayForm($messages['errors']=array()) displayForm($消息[ '错误'] =阵列())

this is actually doing something like this 这实际上是在做这样的事情

$messages['error'] = array(); // set $messages['error'] to an empty array
displayForm($messages['error']); // pass an empty array to displayForm

This is because in PHP, the return value from an assignment is the value assigned. 这是因为在PHP中,赋值的返回值就是赋值。

Why are you using this: 您为什么使用此:

displayForm($messages['errors']=array(),$messages['missing']=array())

When you writing "$messages['errors']=array()" , this is setting $messeges to blank array. 当您编写“ $ messages ['errors'] = array()”时 ,这会将$ messeges设置为空白数组。 So the parameter is blank. 因此参数为空。 You can just write: 您可以这样写:

displayForm($messages['errors'],$messages['missing'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM