Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is GOTO in PHP evil? [closed]

Tags:

php

goto

People also ask

Is goto a bad practice?

"The GOTO statement is generally considered to be a poor programming practice that leads to unwieldy programs. Its use should be avoided."

Should I use goto PHP?

GOTO usually is evil because it lets you build unstructured code. With the usual loops you can build good structured code easy to follow because it is structured.

Why is it bad to use goto?

NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.

Is goto statement still used?

While overall usage of gotos has been declining, there are still situations in some languages where a goto provides the shortest and most straightforward way to express a program's logic (while it is possible to express the same logic without gotos, the equivalent code will be longer and often more difficult to ...


Unless you are programming in assembler, GOTO should always be treated the same way as the life vest of the airplanes: it is good to have them available, but if you need to use them it means that you are in big trouble.


I can't believe nobody posted this :)

xkcd - goto

Granted, PHP is not compiled... Maybe the raptor will chase you on every visit to your website?


Bad structuring of code is evil, regardless the control structure you use.

I personally prefer a goto that makes clear the flow of the program to "control variables" and nested "if" that will indirectly just cause the same branch in the code.

So, just write the two versions (with and without GOTO) and see which one it's easier to comprehend. Then the choice is easy.


I think this is the most important part of the PHP manual page and missing here:

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. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

IMHO this makes it very different from the ye olde BASIC style gotos.


I'm in the minority (currently), but I believe the restrictions placed on PHP's goto construct make a very beneficial tool:

http://adamjonrichardson.com/2012/02/06/long-live-the-goto-statement/

I actually walk through an example of arrow code (deeply nested conditionals) and refactor it using standard practices (guard clauses, grouping conditions, pulling out functions) in one version and a goto-based version in the other version, and I actually prefer the goto-based refactoring.


Are guns evil? Both can be used for good or for evil. I would say it was easier to write good code without goto, than with.