Casting PHP types to string

PHP

Casting PHP types is not easier as it seems. Type juggling in PHP is not obvious. In Java variables can always be represented as strings, without throwing errors. This not the case with PHP and I’ve not found the detailed behavior of string casting in the official documentation. Here it is.
Scalar types (boolean, integer, float and string), NULL and, oddly, ressources can be casted to string without errors. Scalars are converted to their string representation (e.g. 12.3 will become "12.3"), NULL to an empty string and ressources like "Resource id #2".
The going get tough when it comes to array and objects. Arrays are converted to the string "Array" but a notice is thrown. Concerning the objects, no problem if they are instances of classes implementing the magic __toString() method. However, if the class, such as \stdClass or \DateTime,does not implement this method, a catchable fatal error is thrown.

Finally, a code snippet to test if a variable can be casted to the string type:

 

Leave a Reply