Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 'else return' VS auto return

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?

like image 572
Zack Avatar asked Dec 19 '12 02:12

Zack


People also ask

What is the difference between PHP echo and PHP return in function?

Echo is for display, while return is used to store a value, which may or may not be used for display or other use.

What does PHP return do?

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.

What is return false in PHP?

return $oh || false does not work in PHP like it works in JavaScript. It would always return a boolean value (true or false).

How can return true or false function in PHP?

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.


2 Answers

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.

like image 52
Charles Avatar answered Sep 20 '22 03:09

Charles


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!

like image 34
Ali Avatar answered Sep 23 '22 03:09

Ali