效果图:
类代码:
实例
<?php class GirlFirend1 { //声名属性 private $name; private $age; private $height; //构造方法 public function __construct($name='' , $age=0 , $height=0) { $this->name =$name; $this->age =$age; $this->height =$height; } //魔术方法:查询器 public function __get($name) { return $this->$name; //加入检测:访问不存在的属性时给出提示信息 return isset($this->$name)?$this->$name:'无此属性'; } //魔术方法:设置器 public function __set($name, $value) { //不做检测直接设置 // $this->$name = $value; //完善设置器,实现对不存在属性的创建 //如果访问的是已存在的属性,则直接输出 if (isset($this->$name)) { $this->$name = $value; //输出属性 } else { //如果属性不存在,则创建它并保存到类属性$data数组中 $this->data[$name] = $value; } } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
php测试代码:
实例
<?php require './class/GirlFirend1.php'; $girlfirend1 = new GirlFirend1('小小',30,175); //测试魔术方法__get() echo '姓名: ',$girlfirend1->name,'<br>'; echo '年龄: ',$girlfirend1->age, '<br>'; echo '身高: ',$girlfirend1->height, '<br>'; echo '<hr>'; //测试魔术方法: __set() $girlfirend1->name = '娜扎'; $girlfirend1->age = 28; $girlfirend1->height = 178; echo '姓名: ',$girlfirend1->name,'<br>'; echo '年龄: ',$girlfirend1->age, '<br>'; echo '身高: ',$girlfirend1->height, '<br>';
运行实例 »
点击 "运行实例" 按钮查看在线实例