PHP 面向对象高级特性


Defining String Values for Your Objects

Since PHP 5.2,打印一个对象的错误提示

Catchable fatal error: Object of class StringThing could not be converted to string in...

By implementing(实施、实现) a__toString() method, you can control how your objects represent(表现) themselves when printed. __toString() should be written to return a string value. The method is invoked automatically when your object is passed to print or echo, and its return value is substituted. Let’s add a __toString() version to a minimal Person class:

class Person {
    function getName()  { return "Bob"; }
    function getAge() { return 44; }
    function __toString() {
        $desc  = $this->getName();
        $desc .= " (age ".$this->getAge().")";
        return $desc;

The __toString() method is particularly useful for logging and error reporting, and for classes whose main task is to convey information. The Exception class, for example, summarizes exception data in its __toString() method.