Magic Method ___tostring () Example (PHP Object-oriented Advanced tutorial)

Source: Internet
Author: User
As we all know, after we instantiate a class, accessing the properties of a class is accessed in such a format as the name of the property named-----so do you ever try to test the result directly with Echo or print output. Some people say, this should be not possible, will error it. Yes, this direct output does make an error, but when we use the Magic method to __tostring it. The __tostring () method first passes the object to a string in the output so that it can be output with echo or print.

Example Analysis:

<?phpheader ("Content-type:text/html;charset=utf-8"); class Preson{public $name;p rivate $age; function __construct ($name, $age) {$this->name = $name; $this->age = $age;} Public Function __tostring () {return $this->name. ' This year has been '. $this->age. ' old ';}} $preson = new Preson (' xiaoming '); Echo $preson;

Code Analysis:

We first create a human class, define properties, create a constructor method, and then instantiate the class, and finally echo the class name directly. It will be found that the error message will be displayed on the page: Object of Class Preson could not being converted to string with D:\WWW\tostring.php on line 15. This means that the object's class person cannot be converted to a string that cannot be exported. So we add the __tostring () method, so we can return the desired result directly in the method.

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.