Magic _ set () example (php object oriented advanced tutorial)

Source: Internet
Author: User
_ Set (): When you assign a value (private, protected, nonexistent) to an inaccessible attribute, php executes the _ set () method. As we have mentioned above, the function of _ set () is to execute the _ set () method when assigning values to inaccessible attributes (private, protected, and does not exist. _ Set:

_ Set (): php executes the _ set () method when assigning values to inaccessible attributes (private, protected, and does not exist.

As we have mentioned above, the function of _ set () is to execute the _ set () method when assigning values to inaccessible attributes (private, protected, and does not exist.

What does this mean. For example, we use the above example. We replace peaches that monkeys like with bananas, but according to the rules, the keyword before $ food is protected.
But we need to assign a value to $ food. what should we do?

 Name = $ name; $ this-> food = $ food;} function sayHello () {echo'
I am '. $ this-> name. 'I like eating '. $ this-> food;} // magic method function _ get ($ pro_name) {// first judge whether $ pro_name exists if (isset ($ this-> $ pro_name )) {return $ this-> $ pro_name;} else {echo 'property value does not exist ';} function _ set ($ pro_name, $ value) {// first determine whether $ pro_name exists if (isset ($ this-> $ pro_name) {return $ this-> $ pro_name = $ value ;} else {echo 'property value does not exist';} $ monkey = new Monkey ('Monkey ', 'peach') $ monkey-> sayHello (); echo 'Monkey likes to eat '. $ monkey-> food; $ monkey-> food = 'banana '; echo'
'; $ Monkey-> sayHello ();

Because $ food is protected, access is not allowed. Then, we need to use the _ set () magic method. The _ set () method contains two parameters: variable name and variable value. The two parameters cannot be omitted.

The above is the details of the magic method _ set () instance (php object oriented advanced tutorial). For more information, see other related articles in the first PHP community!

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.