I've run into several situations where the rest of a PHP code block needs to be skipped over due to an error condition (database connection error, invalid input, etc.). As a student, my professor simply uses die
, which stops parsing of the file altogether, leaving the page incomplete, without the footer or even the HTML closing tags </body></html>
. Even when there is an error, there is no reason to generate invalid HTML by cutting off the closing tags.
Of course, a purely structured approach would use if
statements, and this is preferable to goto
in the vast majority of situations. However, I feel that if you're just trying to jump out of a PHP code block, putting large segments of code in an if
/else
structure is rather inelegant and can actually make the code harder to understand than simply using a goto
statement that jumps to the very end of the PHP block, just before the ?>
, since it becomes hard to remember that a whole bunch of code is in fact part of a conditional statement 50+ lines below the if
or elseif
lines.
Everyone says that goto
statements are bad, but there are valid uses for goto
that make the code easier to understand, such as jumping out of deeply nested control structures and jumping to the end of a PHP code block (given that no built-in language construct exists for doing that).
A code construct like goto
is not inherently evil. It comes down to how you use it.
if
?goto
butgoto
= poor design... There'sif else
for what you need.break
andcontinue
are for loop-structures only. "break ends execution of the current for, foreach, while, do-while or switch structure." stands in the php documentation.