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 admin Leave a comment Go to comments

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:

<?php

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;

?>

Output:

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:





Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  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

  1. October 26th, 2007 at 22:03 | #1
  2. November 3rd, 2007 at 13:03 | #2
  3. November 5th, 2007 at 22:03 | #3
Enter this code to leave comment (Sorry, but bots get me crazy :) )