use goto inside function php

dav picture dav · Oct 4, 2013 · Viewed 23.5k times · Source

Is there a way to define global label (something like variables) for PHP goto, in order to use it inside function declaration. I want to do the following:

function myFunction() {
   if (condition) {
     goto someLine;
  }
}


someLine:
// ....

myFunction();

when I use this code it says

PHP Fatal error:  'goto' to undefined label "someLine"

I know that it is not recommended to use goto statement. But I need it in my case. I know that perhaps always there are alternatives of goto, just in my case it would make the code a little easier and understandable

Answer

Lemon Drop picture Lemon Drop · Oct 4, 2013

You cannot goto outside of a function I believe: http://php.net/manual/en/control-structures.goto.php

Direct Quote: This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one.

This might have to do with the fact that php is parsed and jumping out of a function will cause a memory leak or something because it was never properly closed. Also as everyone else said above, really you don't need a goto. You can just return different values from the function and have a condition for each. Goto is just super bad practice for modern coding (acceptable if you are using basic).

Example:

function foo(a) {
    if (a==1) {
        return 1;
    } elseif (a==3) {
        return 2;
    } else {
        return 3;
    }
}

switch (foo(4)) { //easily replaceable with elseif chain
    case 1: echo 'Foo was 1'; break; //These can be functions to other parts of the code
    case 2: echo 'Foo was 3'; break;
    case 3: echo 'Foo was not 1 or 3';
}