First look at the explanation of the official PHP documentation:
__set () is run when writing the data to inaccessible properties.
__get () is utilized to reading data from inaccessible properties.
How do you translate it in Chinese?
Inaccessible:n. It is difficult to reach, to be near, to understand.
There is code that has the truth:
Copy Code code as follows:
<?php
Error_reporting (E_all);
Class stu{
Private $a;
Private $b = 0;
Public $c;
Public $d = 0;
The private here can be replaced with protected public.
Private Function __get ($name) {
return 123;
}
Private here can also be replaced with protected public.
Private Function __set ($name, $value) {
echo "This is set function";
}
}
$s = new Stu ();
Var_dump ($s->a); Output:123
Var_dump ($s->b); Output:123
Var_dump ($s->c); Output:null
Var_dump ($s->d); output:0
Var_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, executing var_dump ($s->a) var_dump ($s->b) can have fatal errors
If there is no __get method, execution Var_dump ($s->e) will have a notice, prompting that no attributes are defined $e
Summary:
1. The __get () method is invoked when reading data from an inaccessible property
2. __set () method is invoked when assigning values to a property that is difficult to access
3. Inaccessible Access includes: (1) private properties, (2) Properties not initialized
4. __isset () __unset () is similar