Categories
PHP

PHP __toString() method

Useful to convert objects that, when printed (say in debugging), will give you output like “Resource ID blah blah”, or error messages telling you you can’t print the object.

Example:

class Person {
    function getName()  { return "Bob"; }
    function getAge() { return 44; }
    function __toString() { // Controls how this object will represent itself when printed
        $desc  = $this->getName();
        $desc .= " (age ".$this->getAge().")";
        return $desc;
    }
}
$person = new Person();
print $person; // We get the printout defined in __toString() here...

Leave a Reply

Your email address will not be published. Required fields are marked *