See this name, is not a very high-level feeling. Yes, the Magic method is really advanced.
So, what is a magic method?
The method, which begins with two underscores in PHP, is known as the "Magic Method" (Magic methods). such as __construct (), __destruct (), __clone (), and __call (), __get (), __set (), __sleep (), __wakeup (), __tostring (), __ AutoLoad () and so on, are all magic methods.
If you want PHP to invoke these magic methods, you must first define them in the class, otherwise PHP will not execute the Magic method that was not created.
Attention:
Magic method is set in PHP, so can not be created by themselves, can only be used in PHP exists, or will be error.
Here we introduce the magic methods used in many magic methods.
The role of __get () is:
__get (): PHP executes the __get () method when reading the value of an inaccessible property (private,protected, not present).
Let's take a look at an example of __get ():
<?phpclass monkey{public $name;p rotected $food, function __construct ($name, $food) {$this->name = $name; $this- >food = $food;} function SayHello () {echo ' <br/> I am '. $this->name. ' I like to eat '. $this->food;}} $monkey = new Monkey (' monkey ', ' peach ') $monkey-SayHello ();
The above example is what we said earlier about class knowledge, creating classes, creating methods, instantiating, and finally accessing.
Here we propose a new requirement that we call $food directly outside of the class. Then someone will say that $food is a protected property that cannot be called directly. But the demand is to do so, what to do? This is the time to use our Magic Method __get (). Look at the following code:
<?phpclass monkey{public $name;p rotected $food, function __construct ($name, $food) {$this->name = $name; $this- >food = $food;} function SayHello () {echo ' <br/> I am '. $this->name. ' I like to eat '. $this->food;} Magic method Function __get ($pro _name) {//First determine if $pro_name exists if (Isset ($this, $pro _name)) {return $this $pro _name;} Else{echo ' property value does not exist ';}}} $monkey = new Monkey (' monkey ', ' peach ') $monkey-SayHello (); Echo ' Monkeys like to eat '. $monkey food;
Before using the Magic method, we need to first determine whether $pro_name exists. Because in the above example, the $pro _name call is Food,food, so it can be called. But if food is replaced with something else that does not exist, such as a, then the __get () method will be called, but the error will be that a does not exist. So we have to make a judgment first.