PHP Magic Method: _get () and _set () magical

Source: Internet
Author: User
PHP Magic Method: __get () and __set () magical

?

 _setters) {return $this, $property;    } else if (Method_exists ($this, ' _get_ '. $property)) return Call_user_func (Array ($this, ' _get_ '. $property)); else if (In_array ($property, $this->_getters) OR method_exists ($this, ' _set_ '. $property)) throw new Exception ( ' Property '. $property.    ' Is write-only. '); else throw new Exception (' property '. $property.  ' is not accessible. ');} Public Function __set ($property, $value) {if (In_array ($property, $this->_getters)) {$this, $property = $v    Alue;    } else if (Method_exists ($this, ' _set_ '. $property)) Call_user_func (Array ($this, ' _set_ '. $property), $value); else if (In_array ($property, $this->_setters) OR method_exists ($this, ' _get_ '. $property)) throw new Exception (' property '. $property.    ' Is read-only. '); else throw new Exception (' property '. $property. ' is not accessible. ');}? >this the variables in the $_getters array can be READ from the outside and the variables in the $_setters array can is modified from the outside, like this: 
 title = ' Hello, world '; Echo $post->title;//The following would throw a exception since $comments is read-only: $post-&G T;comments = 23;? >and in case you need a less generic getter or setter at some point, you can remove the variable from the $_getters or $_setters array and implement a method like:
 title = Str_replace (' World ', ' Universe ', $value);}? >and from the outside, the property could still is used with:
 title = ' Hello, world! ';? >

The above is the example in the manual, but I think it should be first to determine whether there is a method of processing the property, some call the method, not directly set the property.

?

  • 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.