简体   繁体   中英

In php, does “return false” do anything after echo statement?

When I display an error message in php, I usually do it like this,

if($query){
    // Success code
}else{
    // Error message
    $error_msg = "An error occurred.";
    return false;
}

and I echo $error_msg variable in the front-end html page. I am just wondering if that return false after the variable actually does anything, or is it just pointless to put it there?

I am trying to optimize my code and just wanted to make sure! Thanks a lot in advance!

Yes, it tells the function to stop executing, and to return a value "false". So it does something. Whether or not is does something USEFUL depends on your programming.

If you have no executable lines after the echo, and the function is not required to return a value, then it won't actually do anything useful.

If does make it clearer to readers that "this is a stop/failure point" though. And one day you might want to actually trap if it worked or failed - so leaving it in makes it clearer. You also may extend the function without thinking and need to retro-fit the returns - again, leaving it in makes it easier.

On the converse, there is also the old programming style from C / Assembler days that you only have one entry and one exit point for all functions to help with garbage collection. Not a requirement with PHP, but that style does make it nice and neat. In this case, set the return value (if required) and return at the end.

So, go with which suits your style - but think ahead. Making everything pristine and minamlistic (ie dropping the line as you don't strictly need it) may not always be the best approach.

The point of the return false is so that you can easily test a function to see if it has worked - without needing to go into any potential error messages and the like.

A function that returns false for a fail can be used in the following manner:

if(someFunction($var))
{
    do stuff for function working...
}
else
{
    // function failed. Do other stuff.
}

It is also intuitive that a function returns false when it fails. It can be further used like this:

$foo=someFunction($var);
if($foo)
{
    again, function has worked.
}//... etc

While the same function returning The function has failed could not be used in tis intuitive manner.

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