Correction status:Uncorrected
Teacher's comments:
输出数据
header("Content-type:text/html;charset=utf-8"); require 'class/GirlFriend2.php'; $gf = new GirlFriend2('xiaoming',28,[80,88,90]); //echo $gf->name; $gf->age = 100; $gf->name = 'xiaoming'; echo $gf->age;
类文件
<?php class GirlFriend2 { private $name; private $age; private $stature; public function __construct($name,$age,$stature=[]) { $this->name = $name; $this->age = $age; $this->stature = $stature; } public function __get($name) { $msg = '没有权限访问'; if ($this->name =='xiaoming'){ $msg = $this->$name; } return $msg; } public function __set($name, $value) { if($name == 'age'){ if(in_array($value, range(12, 120))){ $this->$name = $value; } }else{ $this->$name = $value; } } }
总结访问不到属性或者不存在的属性,给属性设置值,自动调用__set()
不能读取私有属性自动调用__get()
使用__construct()对象属性初始化