This article will introduce you to the usage of the php object-oriented _ toString () method, __tostring () method is automatically called, it is automatically called when an object reference is directly output.
This article will introduce you to the usage of the php object-oriented _ toString () method, __tostring () method is automatically called, it is automatically called when an object reference is directly output.
As we have mentioned earlier, the methods for declaring the method name "--" in the class (provided by PHP) are all automatically called for execution at different times, the "_ toString ()" method is also automatically called, which is automatically called when the object is directly referenced. we have mentioned that object reference is a pointer, for example: in "$ p = new Person ()", $ p is a reference. we cannot use echo to directly output $ p, which will output "Catchable fatal error: object of class Person cocould not be converted to string. if you define the "_ toString ()" method in the class, when you directly output the Object reference, instead of generating errors, the "_ toString ()" method is automatically called to output the characters returned in the "_ toString ()" method. Therefore, the "_ toString () the method must have a return value (return statement ).
The instance code is as follows:
-