Regarding PHP functions, if you do not need a function to return a BOOLEAN or STRING, is there a difference between declaring a return
on failure of a condition, rather than just letting the function automatically return?
For example,
Is there any internal difference between:
function check() {
if( 5 > $v ) {
die('yes');
}
}
function check() {
if( 5 > $v ) {
die('yes');
}
else {
return;
}
}
Obviously, they appear to do the same exact thing on failure of the 'IF' condition, but internally, is one better than the other in for sake of memory, security, usability, or overall best practice?
Echo is for display, while return is used to store a value, which may or may not be used for display or other use.
The purpose of return statement in PHP is to return control of program execution back to the environment from which it was called. Upon returning, execution of expression following the one which invooked other function or module.
return $oh || false does not work in PHP like it works in JavaScript. It would always return a boolean value (true or false).
The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.
There is no effective, real-world difference in these statements in terms of memory or security. None, nada, zip, zero. They are completely identical. The few bytes needed to hold the additional opcodes is irrelevant, and if you care about the time spent parsing, tokenizing and interpreting the opcodes, you are engaging in micro-optimization.
In terms of "usability", the former is more clear by far. Returning from the else
is silly. If I saw that in live code, I'd assume that whoever wrote it was distracted when doing so and clean it up.
return in your second example does nothing instead of increasing parser and compiler work, confusing thee reader what it's rule is, add unnecessary lines to code and increasing the app size in total, and in the end it doesn't have any kind of value!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With