Casting magic in dynamic languages


“Do not meddle in the affairs of Wizards, for they are subtle and quick to anger.”
—J. R. R. Tolkien

Dynamic, weekly-typed languages like Perl and PHP are wonderful productivity engines. It’s amazing how much work one can accomplish with so few lines of code. Both languages allow the programmer to treat simple scalar variables as numbers or strings without a lot of casting or explicit conversions. However, there is a price for this magic.

Consider the following PHP code:

  array_push($array, '"' + $file + "'");

This looks harmless enough. It looks like contents of the $file string are being enclosed in double quotes and that new string is being pushed on the end of $array.

Not so fast! The + operator is a little magical. That is, it operates as a concatenation operator when the operands are strings and as a sum operator when the operands are integers. Wait, didn’t I just say that values are weakly typed in PHP? How can the interpreter tell the difference between strings and ints?

The answer for both Perl and PHP is that strings that start with integers are considered to be integers for the purposes of magic.

In the code sample above, the filename in question indeed started with “2009-09”. PHP took the integer part of the string, 2009, because of the + operator. Then it clearly had a string operand (‘”’) and a integer (2009), so it “promoted” the integer back to a string, “2009”.

And that’s how’s how I lost my filename, which caused me to spend the next 30 minutes debugging the problem.