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 ()