"Getting Started with the PHP object-oriented (OOP) Programming Tutorial" 16.__tostring () method

Source: Internet
Author: User

As we said before, the method that declares the method name of "__" in the class (provided to us by PHP) is the method that executes automatically at a certain time under different circumstances, and the "__tostring ()" method is also automatically called, which is called automatically when the object reference is directly exported. We said before that the object reference is a pointer, for example: "$p =new person ()", $p is a reference, we can not use the Echo Direct output $p, this will output "catchable fatal error:object of class person C Ould not is converted to string "error, if you define a class inside the" __tostring () "method, in the direct output object reference, will not produce an error, but automatically called the" __tostring () "method, output" __ The character returned in the ToString () "method, so the" __tostring () "method must have a return value (return statement).

<?php//Declare A simple classclass testclass{public $foo;p ublic function __construct ($foo) {$this->foo = $foo;} Define a __tostring method, and add a member property $foopublic function __tostring () {return $this->foo;}} $class = new TestClass (' Hello ');//Direct Output object echo $class;? >
Above example output: Hello

"Getting Started with the PHP object-oriented (OOP) Programming Tutorial" 16.__tostring () 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.