The __toString() magic method allows to convert an object to a string. This mechanism can be extended to allow converting to other scalar types. New rules can also allow converting the value, even when the specific method is not implemented.
New magic methods
The first part is easy to understand : we add three new magic methods : __toBool(), __toInt(), and __toFloat().
New conversion rules
When converting an objet to scalar, the conversion logic will be :
- Does a magic method to convert to the destination type exist ? If yes, convert using this method.
- Use a fallback mechanism to search alternate magic methods. When one is found, use it and then convert this interim result to the destination type. If this conversion fails, search the newt one.
Here are the methods that will be searched depending on the target type :
|Target||Try these methods in turn...|
|Bool||Bool Int Float String|
|Int||Int Float String Bool|
|Float||Float Int String Bool|
|String||String Int Float Bool|
In case of a two-step conversion, scalar conversion rules apply.
Conversion can fail, even when a magic method is found :
When a method fails, we try the next one, if any :