Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GOTO command in PHP?

I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?

I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "GOTO 10"-like command...

like image 488
Henrik Paul Avatar asked Aug 21 '08 05:08

Henrik Paul


2 Answers

They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of switch nested if statements. Here's the concept example I found:

<?php
for ($i = 0; $i < 9; $i++) {
    if (true) {
        break blah;
    }
    echo "not shown";
    blah:
    echo "iteration $i\n";
}
?>

Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional COMEFROM joke. Be on your toes.

See also:

http://www.php.net/~derick/meeting-notes.html#adding-goto

like image 134
Ishmaeel Avatar answered Sep 24 '22 16:09

Ishmaeel


I'm always astonished at how incredibly dumb the PHP designers are. If the purpose of using GOTOs is to make breaking out of multiply nested loops more efficient there's a better way: labelled code blocks and break statements that can reference labels:

a:  for (...) {
    b:  for (...) {
         c: for (...) {
               ...
               break a;
           }
       }
   }

Now is is clear which loop/block to exit, and the exit is structured; you can't get spaghetti code with this like you can with real gotos.

This is an old, old, old idea. Designing good control flow management structures has been solved since the 70s, and the literature on all this is long since written up. The Bohm-Jacopini theorem showed that you could code anything with function call, if-then-else, and while loops. In practice, to break out of deeply nested blocks, Bohm-Jacopini style coding required extra boolean flags ("set this flag to get out of the loop") which was clumsy coding wise and inefficient (you don't want such flags in your inner loop). With if-then-else, various loops (while,for) and break-to-labelled block, you can code any algorithm without no loss in efficiency. Why don't people read the literature, instead of copying what C did? Grrr.

like image 34
Ira Baxter Avatar answered Sep 24 '22 16:09

Ira Baxter