Look first. Official DocumentsThe explanation
__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:
error_reporting (E_ALL);
class stu{
private $a ;
private $b = 0;
public $c ;
public $d = 0;
//这里的 private 可以用 protected public 替代
private function __get( $name ) {
return 123;
}
//这里的 private 也可以用 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:
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
The above describes the PHP magic method __set __get method, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.