PHP: Exiting a function
A newbie style question, I'm afraid. I was wondering if someone might tell me what best practice is in the following situatio开发者_JAVA百科n.
Should it be...
function submitted_data()
{
//Testing user data
if(userdata != correctlyentered)
{
display_form(errors);
}
//Submit verified data to server
}
In which case, what's the correct syntax when calling display_form
from within submitted_data
, because at the moment it continues to submit the data to the server when I don't want it to.
Or should it be...
function submitted_data()
{
//Testing user data
if(userdata != correctlyentered)
{
display_form(errors);
}
else
{
//Submit verified data to server
}
}
Or does it not make any difference?
Thanks.
Your second example is valid:
function submitted_data();
{
//Testing user data
if(userdata != correctlyentered)
{
display_form(errors);
}
else
{
//Submit verified data to server
}
}
To "exit" a function, use return
. It could have been done like this:
function submitted_data();
{
//Testing user data
if(userdata != correctlyentered)
{
display_form(errors);
return;
}
//Submit verified data to server
}
If you don't use the else statement and don't write a return statement inside the if, the first example will submit data to the server in every case.
If you want to get out of a function, you need to return
.
Usually, if you're getting out of a function because you detected a problem - you'll return false
so you can code around what happens if the function sends you back a 0/false result.
If your function works as you'd like, use return true
so you can code around what to do when the function did what it was supposed to with no problems.
Of course you can return other things - personally I try to avoid using 'echo' in functions so that I can choose to either keep or output the data in different situations.
So:
function myFunction() {
$result = "something happened";
return $result;
}
echo myFunction();
Would be preferable to:
function myFunction() {
$result = "something happened";
echo $result;
return true;
}
Because I can call myFunction just to test it without having to display the results, or I can choose to display the results. Two birds killed, one stone used.
First off, do not put semicolons after the function declarations.
Anyway, this depends entirely on what you're trying to do. If you add the else (2nd block), the code will only run if userdata != correctlyentered
is FALSE. If you don't add the else (1st block), the code will always run.
Edit:
To exit a function, you can use return
.
if(userdata != correctlyentered)
{
display_form(errors);
return;
}
I think in this case you should choose the variant with the least code nesting inside {}
function submitted_data()
{
//Testing user data
if(userdata != correctlyentered)
{
display_form(errors);
return;
}
//Submit verified data to server
}
精彩评论