Monday, October 31, 2011

Php type cast

Today I have been refactoring code which I wrote half an year ago and I made this mistake:


I wrote 
$url = $someUrl - $file->getName();


instead of
$url = $someUrl . $file->getName();


Suddenly the other code stopped working. However not for subtraction of strings but for something like fopen($url, "w") where $url was invalid. Of course. But question is what is really stored in $url?
In my case there was "/folder/subfolder" in $someUrl and "something.txt" in $file->getName(). The result in $url was ... tamtadadaa ... 0. Ok, when you think about it, it is simple. PHP takes both strings and convert them to numbers and those subtracts. Fine. As I said in my case the result was 0. That is because none of both strings starts with number. In case that the first string was "12 angry men" the result would be "12".
Other example, first string is "12 angry men" and second is "1 angry bird". The result is 11.


There are more similar things in php and you should know them or you'll be surprised one day. For example try echo 0 == "Hello world"