Home > Backend Development > PHP Tutorial > Detailed explanation of magic method __set() instance (php advanced object-oriented tutorial)

Detailed explanation of magic method __set() instance (php advanced object-oriented tutorial)

巴扎黑
Release: 2023-03-07 14:48:01
Original
2651 people have browsed it

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 &#39;<br/>我是&#39; . $this->name . &#39;我喜欢吃&#39; . $this->food;
}
//魔术方法
function __get($pro_name){
//先判断$pro_name是否存在
if(isset($this -> $pro_name)){
return $this -> $pro_name;
}else{
echo &#39;属性值不存在&#39;;
}
}
function __set($pro_name,$value){
//先判断$pro_name是否存在
if(isset($this -> $pro_name)){
return $this -> $pro_name = $value;
}else{
echo &#39;属性值不存在&#39;;
}
$monkey = new Monkey(&#39;猴子&#39; , &#39;桃子&#39;)
$monkey -> sayHello();
echo &#39;猴子喜欢吃&#39; . $monkey -> food;
$monkey -> food = &#39;香蕉&#39;;
echo &#39;<br/>&#39;;
$monkey -> sayHello();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template