PHP Manual Masterpieces

Oct 7

The documentation clearly says raptors.

From the comment section of the documentation on exceptions:

To continue the execution code after throw new Exception, goto operator can be used, like this:

try {
    echo 'one';
    throw new Exception('-error-'); a:
    echo 'two';
} catch (Exception $e) {
    echo $e->getMessage();
    goto a;
//output: one-error-two

AAAAAAAAA - hang on, when did PHP get goto? 5.3? All right then - AAAAAAH WHAT ARE YOU DOING.

Now before you send me hatemail, I’m an asm programmer and I actually like goto, in the proper context. It’s probably a good thing PHP didn’t have goto back in the 4.2 days when I was learning, or I would have thought ‘twas the neatest thing and used it everywhere. PHP’s goto apparently has some restrictions on what sort of scopes you can jump between, which is a good thing.

Apparently, jumping from a catch block into the middle of a try block is not one of these restrictions.

I’m on vacation right now, and I’ve been using this online thingie to test the PHP snippets I’ve been posting about. I just noticed it’s actually still on PHP 5.2, so I haven’t gotten to witness this executing - but I will take it on faith that it works.

Try-catch is one of the most structured concepts there is in programming, and goto is the sworn enemy of that. If you want to make sure that the next thing after an exceptable line in a try block always executes, don’t put it in the same try block! Just put it bare after the try/catch or, if it’s also exceptable, in another try block. (I feel like “exceptable” may not be the scientific term.) Obviously the example in the comment is a proof-of-concept, but you are going to get yourself into trouble so fast like this, unknown commenter. Do not trifle with the gods of program control flow, for they are subtle and quick to segfault. (Normally I wouldn’t worry about segfaulting in an interpreted language, but, well, PHP. It happens.)

Let me put on my security auditor hat. When you use goto to defeat control flow, you are making it a lot freaking harder to verify the correctness of your program. Terrible, wicked bugs will hide in the nooks and crannies of your supposed cunning to devour you. More importantly, your auditor will go looking for her murderin’ axe that she keeps in that closet you’re not allowed to open.

And if you’re still not convinced, if you check the documentation on goto, it clearly says beneath the examples that if you actually use this feature, you will be eaten by raptors. (Who approved this for mainline?!)