7.6.1. ProblemYou want to control how PHP displays an object when you print it. 7.6.2. SolutionImplement a __toString( ) method, as shown in Example 7-14. Defining a class's stringification
7.6.3. DiscussionPHP provides objects with a way to control how they are converted to strings. This allows you to print an object in a friendly way without resorting to lots of additional code. PHP calls an object's __toString( ) method when you echo or print the object by itself, as shown in Example 7-15. Defining a class's stringification
You can write: $rasmus = new Person; $rasmus->setName('Rasmus Lerdorf'); $rasmus->setEmail('rasmus@php.net'); print $rasmus; Rasmus Lerdorf <rasmus@php.net> This causes PHP to invoke the __toString( ) method behind the scenes and return the stringified version of the object. Your method must return a string; otherwise, PHP will issue an error. While this seems obvious, you can sometimes get tripped up by PHP's auto-casting features, which do not apply here. For example, it's easy to treat the string '9' and the integer 9 identically, since PHP generally switches seamlessly between the two depending on context, almost always to the correct result. However, in this case, you cannot return integers from __toString( ). If you suspect you may be in a position to return a non-string value from this method, consider explicitly casting the results, as shown in Example 7-16. Casting the return value
By casting $this->label to a string, you don't need to worry if someone decided to label that text input with a number. The __toString( ) feature has a number of limitations in versions of PHP prior to PHP 5.2. For example, it does not work for interpolated or concatenated strings (see Example 7-17). Invoking __toString( )
The one exception is a dusty corner of PHP that uses echo and a comma (,) instead of period (.) to combine items, as shown in Example 7-18. Invoking object stringification and concateination
Earlier version of PHP 5 will also not autoconvert objects to strings when you pass them to a function that requires a string argument. You should call __toString( ) on them instead (see Example 7-19). Invoking __toString( ) directly
This also applies when you:
Therefore, if you're using __toString( ) heavily in your code, it's best to use PHP 5.2 or greater. |