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 acase
statement is found with a value that matches the value of theswitch
expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of theswitch
block, or the first time it sees abreak
statement. If you don’t write abreak
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 lastcase
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.
Comments
One response to “PHP code rant”
Here Here!