PHP 5 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.
Related Post
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.












































Comments
No comments yet.
Leave a comment