__tostring () is a convenient way to quickly get the string information of an object
The method that is called automatically when the object reference is directly exported.
The role of __tostring ()
When we debug the program, we need to know if we can get the correct data. For example, when printing an object, look at the properties of this object, what the value is, if the class defines the ToString method, in the test, echo prints the object body, the object will automatically call its own class definition of the ToString method, formatted output this object contains data.
Let's look at an example of a __tostring ()
<?phpclass person{ Private $name = ""; function __construct ($name = "") { $this->name = $name; } function say () { echo "Hello,". $this->name. "! <br/> "; } function __tostring () {//define a __tostring method in the class return "Hello,". $this->name. "! <br/> "; }} $WBlog = new Person (' Wblog '), echo $WBlog;//Direct Output object reference automatically invokes the __tostring () method in the object $wblog->say ();//Compare what is the difference between the automatic call above? >
Program output:
hello,wblog!
hello,wblog!
What happens if you don't define the "__tostring ()" Method? For example, on the basis of the above code, the "__tostring ()" method to screen off, and then look at the program output results:
catchable fatal error: Object of class person could not being converted to string
It can be concluded that if the "__tostring ()" method is not defined in the class, the error is generated by the direct output of a reference to the image, and a return value is required in the __tostring () method body.
The Magic function of Object __tostring () is automatically called when the object reference is directly output