Recipe 7.6. Defining Object Stringification


7.6.1. Problem

You want to control how PHP displays an object when you print it.

7.6.2. Solution

Implement a __toString( ) method, as shown in Example 7-14.

Defining a class's stringification

class Person {     // Rest of class here     public function __toString() {         return "$this->name <$this->email>";     } }

7.6.3. Discussion

PHP 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

class Person {     protected $name;     protected $email;     public function setName($name) {         $this->name = $name;     }     public function setEmail($email) {         $this->email = $email;     }     public function __toString() {         return "$this->name <$this->email>";     } }

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

class TextInput {     // Rest of class here     public function __toString() {         return (string) $this->label;     } }

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( )

print  "PHP was created by $rasmus"; print  'PHP was created by  '. $rasmus; printf('PHP was created by %s', $rasmus);

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

echo   'PHP was created by ', $rasmus; PHP was created by Rasmus Lerdorf <rasmus@php.net>

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

print htmlentities($rasmus);                   // bad print htmlentities($rasmus->__toString());    // good

This also applies when you:

  • Place the object inside double quotes or a heredoc

  • Concatenate with the object using dot (.)

  • Cast the object to a string using (string) or strval( )

  • Treat the object as a string in printf( ) by indicating it should be formatted with %s

Therefore, if you're using __toString( ) heavily in your code, it's best to use PHP 5.2 or greater.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net