PHP code rant

This is a mini-rant on PHP that can be safely avoided by non geek types.

This post over on PHP Everywhere caught my attention, vis-a-vis programming semantics and practice. Basically, inside a switch statement, someone placed the default block before the case blocks and was surprised when that default condition executed, and the “expected” case did not.

Some are calling this a bug; I do not. This is the exact behavior I expect switch and default to display, and I always place any default blocks last in the statement, because that makes the most sense semantically and logically. I expect this because that’s how I learned it when learning C years ago; it’s the way the switch construct works and why it’s so fast.

Relevant snippage from the PHP manual:

The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don’t write a break statement at the end of a case’s statement list, PHP will go on executing the statements of the following case….

A special case is the default case. This case matches anything that wasn’t matched by the other cases, and should be the last case statement.

Seems pretty clear to me. I would expect PHP to immediately execute the default block as soon as it encounters it, even if this “cuts off” remaining case blocks below it. So quit complaining and write cleaner code.

Okay, done ranting.

1 comment

Comments are closed.