批改状态:未批改
老师批语:
<?php
//类的声明
class Person
{
//访问限制public,protected,private,属性和方法都有
//公共成员public
//受保护的成员proteced,仅在本类或子类中使用
//私有成员private,仅在本类中使用,子类和外部均不可使用
//一般编程时将属性都私有化,需要调用时用函数调用
private $name;
private $course;
private $score;
const SITE_NAME = 'PHP中文网'; //类常量,可以创建共享数据,时属于雷类的
//构造函数,对象初始化时自动调用
public function __construct($name,$course,$score)
{
$this->name = $name;
$this->course = $course;
$this->score = $score;
//构造方法中也可以调用本类中的方法
$this->show();
}
public function show()
{
return $this->name.'的:'.$this->course.'的分数是'.$this->score;
}
//属性的重载 __set(),__get(),__isset(),__unset()
//在调用不存在或无权访问的属性或方法是自动触发
//__get()获取属性
public function __get($name)
{
if ($name == 'score'){
return $name.'不允许查看';
}
return $this->$name;
}
//设置操作
public function __set($name,$value)
{
if ($name == 'course'){
return $name.'不允许修改';
}
$this->$name = $value;
}
//检测
public function __isset($name){
if ($name == 'score'){
return false;
}
return $this->$name;
}
//销毁
public function __unset($name)
{
if ($name == 'name'){
return false;
}
unset($this->$name);
}
}
//对象初始化,用new关键字
$person = new Person('小明', '语文', '80');
//输出类常量
echo '类中常量:'.Person::SITE_NAME.'<hr>'; //类常量是属于类的,访问时直接类名::类常量
//输出
echo $person->show().'<br>';
echo $person->score.'<hr>';
//设置
$person->course = '数学';
echo $person->course.'<br>'; //返回还是语文
$person->name = '李宁';
echo $person->name.'<hr>';
//检测
echo isset($person->score)?'存在':'不存在'.'<br>';
echo isset($person->course)?'存在':'不存在'.'<hr>';
//销毁
unset($person->course); //无返回值
echo $person->course.'<hr>'; //报错,会提示已经不存在
unset($person->name); //无返回值
echo $person->name.'<hr>';点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号