Wednesday, April 09, 2008

PHP Pop Quiz

What would you expect the following code to do?

$foo = 0;
if ($foo == "DB") {
die("hello world");
die("goodbye world");

I think most rational people would expect the program to exit with the message "goodbye world."

It turns out that PHP is not so rational. Because $foo is a numeric value, it's compared using a numeric comparator with "DB". This typecast coerces "DB" into an integer value 0, so the equality matches.

The solution, of course, is to use the odd === operator which is unique to PHP. This means something along the lines of "I really mean it. No, seriously!" and disables the coercion of the dissimilar types.

The problem with that method, though, is that "0" === 0 evaluates to false.

Is there a reasonable solution to this?


Kevin Smith said...

If it is at all possible, run far, far away from PHP. My company is dealing with a 5 year old mudball codebase of PHP, trying to refactor it into something halfway decent. PHP's inconsistencies make an already difficult job a real PITA.

Lucas said...

Meh. AS3 has the same thing. No language is perfect (except maybe erlang).

Kevin Smith said...

I think AS3 is a different situation since you don't really have many alternatives, AFAIK, for what it does. PHP purports to be more of a general purpose langauge. There better ones of those out there than PHP.

Todd said...

Kevin: have you checked out thrift? We use it to move complicated stuff (e.g. search, transaction processing, etc) to backend services written in other languages (primarily Erlang and Java).

Lucas said...

Kevin: I'm not totally disagreeing. PHP is nowhere close to say Python or Ruby when it comes to merits as a general purpose language. Like actionscript or javascript or lingo etc it has a few things it does well given the use case. Off load the stuff a language doesnt do well to one that does. Can we all agree to stop writing HTML templates for full pages in javascript and stay the hell away from process control in PHP?

Anonymous said...

The code all makes perfect sense to me. The === operator simply makes sure the two variables you are comparing are of the same type. If you compare a string with a number using === then the result is always false.