Php object-oriented _ toString () usage details

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

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.