PHP5 Tutorial - Magic Methods - __toString() method

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@domain.com”);

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

?>

Output:

Customer Object is >> Debug message from Customer Class : First Name = Sunil, Last Name = Bhatia, Email = email@domain.com

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:

Your email:  
Subscribe Unsubscribe  




del.icio.us Reddit Slashdot Digg Facebook Technorati Google StumbleUpon Windows Live Furl Netscape Yahoo Bloglines Bookmark.it Ask Spurl Diigo

3 Responses to “PHP5 Tutorial - Magic Methods - __toString() method”

  1. […] Articles: PHP5 OOPS - Magic Methods __toString() PHP5 OOPS […]

  2. […] Similarly, when the program calls unset() on the undeclared variable i.e. $c->name, the PHP5 magic method __unset() is invoked that takes the name of the undeclared variable i.e. ‘name’ and unsets the internal array $data[’name’]. Related Posts: PHP5 OOPS Tutorial __get() and __set() PHP5 Tutorial - Magic Methods - __toString() method […]

  3. […] PHP5 Tutorial - Magic Methods - __toString() method […]

Leave a Reply

Top Internet blogs Programming Blogs - Blog Catalog Blog Directory TopOfBlogs Technology blogs Top Blog Topsites List