Home > Article > Backend Development > Detailed explanation of magic method __set() instance (php advanced object-oriented tutorial)
The role of
__set():
__set(): When assigning a value to an inaccessible attribute (private, protected, does not exist), PHP will execute the __set() method .
We said above that the function of __set() is: when assigning a value to an inaccessible attribute (private, protected, does not exist), PHP will execute the __set() method.
What does this mean? For example, let's take the above example as an example. We replaced the peaches that monkeys like to eat with bananas, but according to the rules, the keyword in front of $food is protected
and cannot be accessed directly, but we need to assign a value to $food. What should we do?
<?php class Monkey{ public $name; protected $food; function __construct($name,$food){ $this->name = $name; $this->food = $food; } function sayHello(){ echo '<br/>我是' . $this->name . '我喜欢吃' . $this->food; } //魔术方法 function __get($pro_name){ //先判断$pro_name是否存在 if(isset($this -> $pro_name)){ return $this -> $pro_name; }else{ echo '属性值不存在'; } } function __set($pro_name,$value){ //先判断$pro_name是否存在 if(isset($this -> $pro_name)){ return $this -> $pro_name = $value; }else{ echo '属性值不存在'; } $monkey = new Monkey('猴子' , '桃子') $monkey -> sayHello(); echo '猴子喜欢吃' . $monkey -> food; $monkey -> food = '香蕉'; echo '<br/>'; $monkey -> sayHello();
Because our $food is protected, access is not allowed. Then, we have to use the __set() magic method to achieve it. The __set() method contains two parameters, representing the variable name and variable value respectively. The two parameters cannot be omitted.
The above is the detailed content of Detailed explanation of magic method __set() instance (php advanced object-oriented tutorial). For more information, please follow other related articles on the PHP Chinese website!