繁体   English   中英

PHP函数参数默认值

[英]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.

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