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
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:
switchstatement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a
casestatement is found with a value that matches the value of the
switchexpression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the
switchblock, or the first time it sees a
breakstatement. If you don’t write a
breakstatement 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
defaultcase. This case matches anything that wasn’t matched by the other cases, and should be the last
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.