I'm working with/on an extremely antiquated site that I wouldn't put my name to. There seems to a re-occuring pattern in the existing code, along the lines of:
function foo() {
$a = 'a';
$b = 'b';
return;
$c = 'c';
$d = 'd';
}
I'm very relunctant to delete existing code from a function that I didn't write, and everything is working as is. But I would like to know why?
Everything I ever learnt (with the exception of a goto line call) tells me that the code following the return statement is useless. Is it? Why would the previous programmer do this?
The only way you could usefully have code after a "return" is if the "return" statement is conditional. This isn't great coding style, you're creating code where there are 2+ ways to exit. When you need to debug it you'll find it more challenging to put in flags and "what happened when we exited" and so forth.
A return statement causes execution to leave the current function and resume at the point in the code immediately after where the function was called. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.
Calling an statement after return is possible using finally , but it would be easier (and cleaner) to store the result of calling something else and return it later. function b() { echo "bar"; return 2; } function a() { try { echo "foo"; return b(); } finally { echo "finally"; } } echo a();
Yes, the finally block will be executed even after a return statement in a method.
That code after the return
statement will never be executed. most probably the original developer wanted to quickly test other values for the variables and left his old experiments in the function. Use version control and you can delete obsolete code and still recover it, in case you ever need it again.
The code beneath the return statment is useless, it will not be executed.
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