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(“Hiren”,”Prajapati”,”email@domain.com”);
echo “Customer Object is >>” . $c;
?>
Output:
Customer Object is >> Debug message from Customer Class : First Name = Hiren, Last Name = Prajapati, 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:

No comments: