Correction status:qualified
Teacher's comments:
<?php class Honda { // 声明属性 private $name; private $level; private $price; private $data=[]; public function __construct($name='', $level='A0', $price=0) { $this->name = $name; $this->level = $level; $this->price = $price; } public function __set($name, $value) { if (isset($this->$name)) { $this->$name = $value; } else { // 如果属性不存在,则创建它并保存到类属性$data数组中 $this->data[$name] = $value; } } 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; } }
点击 "运行实例" 按钮查看在线实例
<?php require 'class.php'; $Honda = new Honda('Accord','B',179800); // 魔术方法__get echo '名字:',$Honda->name,'<br>'; echo '级别:',$Honda->level,'<br>'; echo '售价:',$Honda->price,'<br>'; echo '<hr>'; // 魔术方法 __set $Honda->name='Civic'; $Honda->level='A'; $Honda->price=139900; echo '名字:',$Honda->name,'<br>'; echo '级别:',$Honda->level,'<br>'; echo '售价:',$Honda->price,'<br>'; $Honda->color='black'; echo '颜色:',$Honda->color,'<br>'; echo '颜色:(自定义属性)',print_r($Honda->data);
点击 "运行实例" 按钮查看在线实例