__set and __get Methods in PHP

Source: Internet
Author: User

When calling or setting a method that does not exist for a class, _ invokes the _set and __get methods

The following is an example
<?phpclass handsonboy{    Private $name = ' Chenqionghe ';    Private $age =;    Public Function __set ($name, $value)    {        echo ' You are setting private properties '. $name. ' <br > value for '. $value. ' <br> ';        $this $name = $value;    }    Public Function __get ($name)    {        if (!isset ($this, $name))        {            echo ' is not set '. $name;            $this, $name = "Setting default values for you". <br> ';        }        return $this $name;    }} $a = new Handsonboy (); Echo $a->name. ' <br/> '; $a->hair = ' short ';
PHP overloads differ from languages such as Java. In Java, overloading refers to a class where you can define multiple methods that have different parameter lists but have the same name. For example, Java also has a constructor, as long as the method signature is not the same as the line; PHP allows only one constructor in a class. PHP provides overloads that dynamically create class properties and methods. Therefore, the __set and __get methods are grouped into overloads.

__set and __get Methods in PHP

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.