简体   繁体   中英

PHP Function Argument Default Value

Hey all. I have a processForm function and a displayForm function. If there are missing form fields the processForm function returns an array of missing fields. This is all fine and dandy until I try to include this array into the displayForm function. 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. However, this overwrites the array returned by the processForm function.

I hope I'm clear. Thanks for any help.

Full Code:

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;

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())

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.

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. So the parameter is blank. You can just write:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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