Search code examples
phpgoto

php goto variable


I wonder if something like this is possible in PHP

$goto = 'end';
goto $goto;

when I use it I get Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING.

Furthermore, how would I do something like this (considering a() returns true or false)

a() or goto end;

as opposed to the longer version

if (!a()) goto end;
  • purely theoretically :)

This has certainly got a lot of reaction. I think mentioning two of PHP's most debated areas (goto and eval) helped get some strong reactions.

Just to get things clear and put some people's hearts at ease: I know the reasons for not using goto. But to every "rule" there are exceptions.


Solution

  • Goto works only like this

    10:
    //something
    
    goto 10;
    

    or

    end:
    //something
    
    goto end;
    

    but yours one is impossible

    Yes, I know using goto is discouraged, but an answer to the actual question is a lot better than these saying DO NOT USE GOTO GOTO IS EVIL

    Addendum: eval goto

    It's not likely you really want to do that:

    $goto = 'end';
    
    eval(<<<EOD
    
        goto $goto;
        return; 
    
        end: 
    
        echo 'end';
    EOD
    );
    

    Demo