🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### __get() 获得不可访问的属性的值: __get() 一旦定义了__get()魔术方法,获取不可访问的属性的值的时候,就会自动的执行该方法,此时,处理权就交给用户自己了! 该魔术方法,只需要一个参数,就是该属性的属性名! ### 默认行为 ~~~ class Person{ public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $p = new Person("jack",20); var_dump($p->height); ~~~ ~~~ Notice: Undefined property: Person::$height //报错 ~~~ ### 不完成方法体 ~~~ class Person{ public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function __get($name) //自动调用__get() ,但是该方法什么都没做 { } } $p = new Person("jack",20); var_dump($p->height); ~~~ ~~~ NULL ~~~ ### 完成方法体 ~~~ class Person{ public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function __get($name) { if(!isset($this->$name)){ return "属性不存在"; } } } $p = new Person("jack", 20); var_dump($p->height); ~~~ ~~~ string(15) "属性不存在" ~~~ 或者 ~~~ class Person{ private $name; private $age; private $money; public function __construct($name) { $this->name = $name; } public function setName($name) { $this->name = $name; } public function __get($name) { $allow_get = ['name', 'age']; if(in_array($name, $allow_get)){ return $this->$name; } return "无权访问"; } } $p1 = new Person("jack"); var_dump($p1->money); ~~~ ~~~ string(12) "无权访问" ~~~ ### 注意 __get和__set两个方法往往在真实的项目中都是成对出现的!而且,往往就是利用这两个方法批量的对对象的私有属性进行处理!