PHP--Object output of the Magic Method: __tostring ()

Source: Internet
Author: User

Object output: __tostring ()

When an object is output as a string (Echo,print), the __tostring () method is called

<?PHP//Output Object    classperson{//Properties         Public$name; Private$age; //Method         Publicfunction __construct ($name, $age) {$ This->name =$name; $ This->age =$age; }         Publicfunction Setage ($age) {$ This->age =$age; }         Publicfunction Getage () {return$ This-Age ; }        //object to String method//requires that only data of type string be returned         Publicfunction __tostring () {//return the properties of the object you want to output//organizing the language for output (controlling the output of attributes)            return(string)($ This->name.':'. $ This-Age ); }    }    //instantiation of$person =NewPerson ('Zhou Zhijo', the); //Var_dump ($person); //Echo $person; //object cannot be exported as a string//Requirements: Echo object, all attributes in the output object (all attributes are concatenated into a single string)Echo $person;

PHP--Object output of the Magic Method: __tostring ()

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.