Using goto inside php function

Is there a way to define a global label (something like variables) for PHP goto to use it inside a 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 the goto operator. But I need it in my case. I know that maybe there are always goto alternatives, just in my case it will make the code a little easier and more understandable

+7
php goto
source share
4 answers

You cannot go beyond the function that I consider: http://php.net/manual/en/control-structures.goto.php

Direct Quote: This is not a complete unlimited transition. The target label must be in the same file and context, which means that you cannot jump out of a function or method and cannot go into one.

This may be due to php being parsed and jumping out of a function will cause a memory leak or something else because it has never been properly closed. In addition, as everyone said above, in fact, you do not need goto. You can simply return different values ​​from the function and have a condition for each. Goto is just 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'; } 
+6
source share

Unable to switch to or exit a function. But since you state that you need it, here is an alternative route.

 function myFunction() { if (condition) { return true; } return false; } someLine: // .... $func = myFunction(); if($func == true) goto someLine; 
+2
source share

As already mentioned, you cannot. As for β€œI need this,” I highly doubt it. Whatever code you have in someLine: you can easily turn it into a function that you can call from another, if necessary.

+2
source share

Yes, there is a way while this function is declared in one php file or is included if it is in another script,

the best way to switch to someline is to return this dude goto code so that if the function is called a return value, 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 */ 
0
source share

All Articles