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 (i.e. dropping the line as you don’t strictly need it) may not always be the best approach.