Home > PHP, PHP Tutorials, PHP5 Magic Methods, PHP5 OOPS Tutorials, Programming > PHP5 Tutorial – Magic Methods – __toString() method

PHP5 Tutorial – Magic Methods – __toString() method

October 25th, 2007

PHP5 provides a magic method by the name of __toString() (double underscore followed by toString()) which is useful for debugging purposes.

The __toString() method is automatically called when an object in PHP5 is converted into a string for the purpose of display or concatenation.

Following is the example of the __toString() method:


class Customer {
private $firstName, $lastName, $email;

public function __construct($firstName, $lastName, $email) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->email = $email;

public function __toString() {
return “Debug message from Customer Class : First Name = ” . $this->firstName . “, Last Name = ” . $this->lastName . “, Email = ” . $this->email;

$c = new Customer(“Sunil”,”Bhatia”,”[email protected]”);

echo “Customer Object is >>” . $c;



Customer Object is >> Debug message from Customer Class : First Name = Sunil, Last Name = Bhatia, Email = [email protected]

See how in this example $c Customer Object got converted into a string type when used with the dot (.) concatenation operator. In the background the magic method __toString() is automatically called when such a conversion happens.

Security Tip:
Be careful not to include sensitive data as part of the output as you could compromise security by leaking secure information. Many applications are written to write object states in a log file, therefore you should ensure that sensitive information like Credit Card information, etc is not made available through the magic method __toString()

Subscribe to my newsletter and be informed as a new PHP5 tutorial is posted online:

  1. shahanaz
    March 19th, 2010 at 00:41 | #1

    Very useful

  2. Manish Patel
    February 3rd, 2012 at 08:47 | #2

    this is very helpfully for me to understand magic method function

Comments are closed.