Question

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

Was it helpful?

Solution

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';
}

OTHER TIPS

There's no way to jump in or out of a function. But since you state that you need it, here's an alternative route.

function myFunction() {
   if (condition) {
     return true;
   }
   return false;
}


someLine:
// ....

$func = myFunction();
if($func == true) goto someLine;

As previously stated you can't. As for "I need it", I highly doubt this. Whatever code you have at someLine: can easily be made into a function that you can call from the other if needed.

yeah there's a way as long as that function is declared on the same php file or is included if its on another script,

the best way to jump on to someline is to return that goto code of yours dude so that if function is called a return value is received.. hope this helps

 function foo($b="30")
 {
 $a=30;
 if($a==intval($b))
 return "someline:goto
 someline";
 }

try{
eval(foo());
}
catch(IOException $err)
{
 exit($err);
}

/*someline is somewhere here   
for example */
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top