The Magic function of Object __tostring () is automatically called when the object reference is directly output

Source: Internet
Author: User

__tostring () is a convenient way to quickly get the string information of an object

The method that is called automatically when the object reference is directly exported.

The role of __tostring ()

When we debug the program, we need to know if we can get the correct data. For example, when printing an object, look at the properties of this object, what the value is, if the class defines the ToString method, in the test, echo prints the object body, the object will automatically call its own class definition of the ToString method, formatted output this object contains data.

Let's look at an example of a __tostring ()

<?phpclass person{     Private $name = "";     function __construct ($name = "") {                   $this->name = $name;      }     function say () {             echo "Hello,". $this->name. "! <br/> ";       }    function __tostring () {//define a __tostring method in the class               return  "Hello,". $this->name. "! <br/> ";        }} $WBlog = new Person (' Wblog '), echo $WBlog;//Direct Output object reference automatically invokes the __tostring () method in the object $wblog->say ();//Compare what is the difference between the automatic call above? >    

  

Program output:

hello,wblog!

hello,wblog!

What happens if you don't define the "__tostring ()" Method? For example, on the basis of the above code, the "__tostring ()" method to screen off, and then look at the program output results:

    catchable fatal error: Object of class person could not being converted to string

It can be concluded that if the "__tostring ()" method is not defined in the class, the error is generated by the direct output of a reference to the image, and a return value is required in the __tostring () method body.

The Magic function of Object __tostring () is automatically called when the object reference is directly output

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.