批改状态:合格
老师批语:
创建类:
<?php
class GirlFriend3 {
//声明属性
private $name;
private $age;
private $stature;
private $data=[];
//构造方法
public function __construct($name='',$age=0,array $stature=[])
{
$this->name = $name;
$this->age = $age;
$this->stature = $stature;
}
//魔术方法:查询器
public function __get($name)
{
// return $this->$name;
//加入检测:访问不存在的属性时给出提示信息
// return isset($this->$name)?$this->$name:'无此属性';
//如果类中添加一个自定义的数据收集器$data,就从这里取值
$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)
{
//不做检测直接设置
// $this->$name = $value;
//完善设置器,实现对不存在属性的创建
//如果访问的是已存在的属性,则直接输出
if (isset($this->$name)) {
$this->$name = $value; //输出属性
} else {
//如果属性不存在,则创建它并保存到类属性$data数组中
$this->data[$name] = $value;
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号