O'Reilly logo

PHP 5 Power Programming by Derick Rethans, Stig Sæther Bakken, Andi Gutmans

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.17. __toString() Method

Consider the following code:

class Person {
    function __construct($name)
    {
        $this->name = $name;
    }

    private $name;
}

$obj = new Person("Andi Gutmans");

print $obj;
It prints the following:
Object id #1

Unlike most other data types, printing the object's id will usually not be interesting to you. Also, objects often refer to data that should have print semantics—for example, it might make sense that when you print an object of a class representing a person, the person's information would be printed out.

For this purpose, PHP enables you to implement a function called __toString(), which should return the string representation of the object, and when defined, the print command will call it and print the returned string. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required