Php object-oriented toString ()
_ ToString ()
When debugging a program, we need to know whether the data is correct. For example, when printing an object, you can check what attributes and values the object has. if the class defines the toString method, echo can print the object body during the test, the object automatically calls the toString method defined by the class to format and output the data contained in the object.
Next we will look at an instance of _ toString ().
Name = $ name;} function say () {echo "Hello,". $ this-> name ."!
";} Function _ tostring () {// define a _ toString method in the class return" Hello, ". $ this-> name ."!
";}}$ Bindao = new Person ('binda'); echo $ Bindao; // The _ toString () method $ WBlog-> say (); // compare it with the above automatic call. what is the difference?>
Program output:
Hello, Bindao!
Hello, Bindao!
What if the "_ tostring ()" method is not defined? For example, based on the code above, block the "_ tostring ()" Method and look at the output result of the program:
Catchable fatal error: Object of class Person cocould not be converted to string
It can be seen that if the "_ tostring ()" method is not defined in the class, an error will occur when the reference to the image is directly output. In addition, _ tostring () the method body must have a return value.