Let's take a look at the explanations of the PHP official documentation:
__set () is the run when writing data to inaccessible properties.
__get () is utilized for reading data from inaccessible properties.
How do you translate it in Chinese?
Inaccessible:n. Hard to reach, difficult to access, incomprehensible.
There is the truth in code:
<?PHPerror_reporting(E_all);classstu{Private $a; Private $b= 0; Public $c; Public $d= 0; //the private here can be replaced with protected public Private function__get ($name) { return123; } //The private can also be replaced with protected public Private function__set ($name,$value) { Echo"This is set function"; }} $s=NewStu ();Var_dump($s->A);//output:123Var_dump($s->B);//output:123Var_dump($s->C);//Output:nullVar_dump($s->D);//output:0Var_dump($s->E);//output:123 $s->a = 3;//Output:this is set function$s->c = 3;//No output$s->f = 3;//Output:this is set function?>
Results Analysis:
If there is no __get method, execution of Var_dump ($s->a) var_dump ($s->b) can have fatal errors
If there is no __get method, the execution of Var_dump ($s->e) has a notice, prompting that no attribute is defined $e
Summarize:
1. When reading data from an inaccessible property, the __get () method is called
2. When assigning values to an inaccessible property, the __set () method is called
3. Difficult to access includes: (1) Private attributes, (2) Properties without initialization
4. __isset () __unset () is similar
(Transferred from Http://www.cnblogs.com/glory-jzx/archive/2012/05/23/2514173.html)
Detailed PHP Magic Methods __get () and __set ()