Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code after a return statement in a PHP function

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?

like image 468
Chris Avatar asked Jun 25 '11 13:06

Chris


People also ask

Can you put code after a return statement?

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.

What happens to code written after the return statement in a function?

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.

How do you call a function after a return?

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();

Does code after return statement get executed?

Yes, the finally block will be executed even after a return statement in a method.


2 Answers

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.

like image 52
knittl Avatar answered Sep 20 '22 14:09

knittl


The code beneath the return statment is useless, it will not be executed.

like image 40
Nahydrin Avatar answered Sep 20 '22 14:09

Nahydrin