Home > PHP > PHP5 Tutorial – __toString() Magic Method

PHP5 Tutorial – __toString() Magic Method

This tutorial will guide you through the __toString() Magic Method. The __toString() Magic method in PHP5 get called while trying to print or echo the class objects. This method can be used print all the methods and attributes defined for the class at runtime for debugging. Also this method can be used to give error message while somebody tries to print the class details.

Syntax:

< ?
function __toString()
{
	...
}
?>

Example – __toString() Magic Method Call

< ?
class magicmethod
{
 
	function __toString()
	{
		return "Caught You!! Cannot access the Class Object";
	}
 
}
$a = new magicmethod();
echo $a;
?>

Output: Caught You!! Cannot access the Class Object
Explanation for the Example:

Here i am trying to echo the object of magicmethod class and the php compiler executes the __toString method which throws an error message.


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: PHP Tags: ,