Php object-oriented toString ()

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.