Correction status:Uncorrected
Teacher's comments:
<?php /** * */ class StaffInfo{ private $name; private $age; private $sanwei; private $data=[]; //构造方法 public function __construct($name='',$age=0,array $sanwei=[]) { $this->name = $name; $this->age = $age; $this->sanwei = $sanwei; } //魔术方法:查询器 public function __get($name) { $msg = null; if(isset($this->$name)){ $msg = $this->$name; }elseif(isset($this->data[$name])){ $msg = $this->data[$name]; }else{ $msg = '没有找到这个属性'; } return $msg; } //魔术方法:设置器 public function __set($name,$value) { if (isset($this->name)) { $this->$name = $value; }else{ $this->$data[$name] = $value; } } }
点击 "运行实例" 按钮查看在线实例
<?php require './class/StaffInfo.php'; $staffinfo = new StaffInfo('朱老师',36,[65,65,65]); //测试魔术方法 __get() echo '姓名:',$staffinfo->name,'<br>'; echo '年龄:',$staffinfo->age,'<br>'; echo '三围:',print_r($staffinfo->sanwei,true),'<br>'; //测试一个不存在的属性 echo '爱好:',$staffinfo->aihao,'<br>'; echo '<br>'; //测试魔术方法 __set() $staffinfo->name = '灭绝小师妹'; $staffinfo->age = 24; $staffinfo->sanwei = [75,60,72]; echo '姓名:',$staffinfo->name,'<br>'; echo '年龄:',$staffinfo->age,'<br>'; // echo '身高:',print_r($staffinfo->sanwei,true),'<br>'; echo '胸围:',$staffinfo->sanwei[0],'<br>'; echo '腰围:',$staffinfo->sanwei[1],'<br>'; echo '臀围:',$staffinfo->sanwei[2],'<br>'; //测试一个自定义的属性 $staffinfo->kecheng = '前端'; echo '所教课程:',$staffinfo->kecheng,'<br>';
点击 "运行实例" 按钮查看在线实例