Understanding and using the _ set () and _ get () interceptors in PHP, __set _ get

Source: Internet
Author: User

Understanding and using the _ set () and _ get () interceptors in PHP, __set _ get

"In general, class attributes are always defined as private, which is more in line with the actual logic.

However, attributes are read and assigned frequently. Therefore, in PHP5, we predefine the two functions "_ get ()" and "_ set () to obtain and assign values to the attributes, and check the "_ isset ()" and the method "_ unset ()" for deleting the attributes ()".

We set and obtain each attribute. In PHP5, we provide a method specifically for setting and obtaining values for the attribute, "_ set () "and" _ get () "methods. These two methods do not exist by default, but are manually added to the class, like the constructor (_ construct (), the class will only exist after it is added. You can add these two methods in the following way. Of course, you can also add them in your own style:"

<? Php // use the class Computer {private $ name; private $ price; private $ cpu; private $ clocked; // assign the value of public function _ set ($ key, $ value) {// then: $ key = name $ value = "Lenovo" has: $ this-> name = "Lenovo" return $ this-> $ key = $ value;} // value of the interceptor public function _ get ($ key) {if (isset ($ key) {// then: $ key = name is $ this-> name, so it is natural to return "Lenovo" return $ this-> $ key;} else {return NULL ;}}} // because the interceptor exists, $ computer = new Computer (); $ computer-> name = "Lenovo"; $ computer-> price = 5600 can be used in this way; $ computer-> cpu = "Eight cores"; $ computer-> clocked = "1600 hz"; echo $ computer-> name; echo $ computer-> price; echo $ computer-> cpu; echo $ computer-> clocked;

The above is a brief introduction to the understanding and usage of the PHP interceptor _ set () and _ get (). I hope you can provide more support ~

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.