_ 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!