批改状态:合格
老师批语:
类、构造器、__get()、__set()
<?php
class Student
{
private $name = '';
private $sex = 0;
private $age = 0;
private $id = 0;
private $grade = [];
private $data = [];
public function __construct($name, $sex, $age, $id, $grade)
{
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
$this->id = $id;
$this->grade = $grade;
}
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/Student.php';
$student1 = new Student('小明', 0, 18, 1234567, [95, 96, 88, 79]);
echo '姓名: ',$student1->name,'<br>';
echo '年龄: ',$student1->age,'<br>';
echo '学号: ',$student1->id,'<br>';
echo '成绩: <pre>',print_r($student1->grade, true),'<br>';
echo '身高: ',$student1->tall,'<br>';
$student1->tall = 180;
echo '身高: ',$student1->tall,'<br>';点击 "运行实例" 按钮查看在线实例

总结:
__get()、__set(): 魔术方法,可以访问和设置对象的私有属性
对于传入的属性,可以进行判断,如果有则输出,如果没有则可以进行设置,作为用户自定义属性添加进去
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号