First take a look at the explanation of the official document
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
How to translate it in Chinese? inaccessible: n. Difficult to reach; difficult to approach; incomprehensible.
There is code and there is truth:
<?php
error_reporting (E_ALL);
class stu{
private $a ;
private $b =
0;
public $c ;
0;
//Here
private can be replaced by protected public
private function __get( $name )
{
//Here
private can also be replaced by protected public
private function __set( $name ,
$value )
{
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
?> There will be a fatal errorIf there is no __get method, there will be a notice when executing var_dump($s->e), prompting that the attribute $e is not defined Summary: 1. When reading data from an inaccessible attribute The __get() method is called2. The __set() method is called when assigning a value to an inaccessible property3. Inaccessible properties include: (1) private properties, (2) uninitialized properties 4. __isset () __unset() is also similar
The above introduces the PHP magic method __set __get method, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.
|