When you see this name, it gives you a very high-end feeling. Yes, magic methods are indeed advanced.
So,What is the magic method?
Methods starting with two underscores in PHP are called "Magic methods". For example, the __construct(), __destruct (), __clone() mentioned before, and __call(),,__get(), __set(),__sleep(), __wakeup(), __toString(), __autoload(), etc., They are all magic methods.
If you want PHP to call these magic methods, you must first define them in the class, otherwise PHP will not execute uncreated magic methods.
Note:
The magic method is set in PHP, so you cannot create it yourself. You can only use what already exists in PHP, otherwise an error will be reported.
Below we will introduce the commonly used magic methods among many magic methods.
__get() functions as:
__get(): When reading the value of an inaccessible attribute (private, protected, does not exist), php will execute __get() method.
Let’s take a look at an example about __get():
name = $name; $this->food = $food; } function sayHello(){ echo '
我是' . $this->name . '我喜欢吃' . $this->food; } } $monkey = new Monkey('猴子' , '桃子') $monkey -> sayHello();
The above example is the knowledge about classes we have talked about before, creating classes, creating methods, instantiating, and finally accessing .
Next we put forward a new requirement, that is, we need to call $food directly outside the class. Then some people will say that $food is a protected attribute and cannot be called directly. But the demand is to do this, what should we do? This is when our magic method __get() is used. Look at the following code:
name = $name; $this->food = $food; } function sayHello(){ echo '
我是' . $this->name . '我喜欢吃' . $this->food; } //魔术方法 function __get($pro_name){ //先判断$pro_name是否存在 if(isset($this -> $pro_name)){ return $this -> $pro_name; }else{ echo '属性值不存在'; } } } $monkey = new Monkey('猴子' , '桃子') $monkey -> sayHello(); echo '猴子喜欢吃' . $monkey -> food;
Before using the magic method, we need to first determine whether $pro_name exists. Because in the above example, $pro_name calls food, and food exists, so it can be called. But if food is replaced by something else that does not exist, such as a, then the __get() method will be called, but an error will be reported, saying that a does not exist. So we have to make a judgment first.
The above is the detailed content of Detailed explanation of magic method __get() instance (php advanced object-oriented tutorial 2). For more information, please follow other related articles on the PHP Chinese website!