php的魔术方法__get()和__set()使用介绍,需要的朋友可以参考下
先看看php官方文档的解释: __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties.
究竟用中文怎么翻译呢? inaccessible :n. 难达到;难接近;无法理解。
有代码有真相: 复制代码 代码如下: <?php 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 ?>