Let’s take a look at the explanation in the official PHP documentation:
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties. What is the use of
How to translate it into Chinese?
inaccessible: n. Difficult to reach; difficult to approach; incomprehensible.
There is code and there is truth:
Copy code The code is as follows:
error_reporting(E_ALL);
class stu{
private $a;
private $b = 0;
public $c;
public $d = 0;
//Here private can be replaced by protected public
private function __get($name) {
return 123;
}
//private here can also be replaced by 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
?>
Result analysis: If there is no __get method, executing var_dump($s->a) var_dump($s->b) will cause a fatal error
If there is no_ _get method, when executing var_dump($s->e), there will be a notice that the attribute $e is not defined
Summary: 1. Read from an inaccessible attribute When fetching data, the __get() method is called
2. When assigning a value to an attribute that is difficult to access, the __set() method is called
3. Inaccessibility includes: (1) private attributes, (2) Uninitialized attributes
4. __isset() __unset() is similar
http://www.bkjia.com/PHPjc/325964.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325964.htmlTechArticleLet’s first look at the explanation in the official PHP documentation: __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties. How to use Chinese...