批改状态:合格
老师批语:
<?php
//编程1: 类声明与类的实例化;
//编程2: 类常量与类属性的重载;
//编程3: 类的继承与方法重写;
//编程4: 类中静态成员的声明与访问
//编程1:类的声明
//父类
class Human {
private $name = '';
private $age = 0;
const SITI_NAME = 'pathon';
public function __construct($name,$age) //构造方法
{
$this->name = $name;
$this->age = $age;
}
}
////编程3: 类的继承 student是human的子类
class Student extends Human {
//private $name = null;
//private $age = 0;
private $grade = null;
private $sex = 1;
//编程2:类常量的声明
const SITI_NAME = 'java';
//编程4: 类中静态成员的声明
public static $static = 1;
public function getSex() {
return ($this->sex = 0) ? '女' : '男';
}
public function __construct($name,$age,$grade) //构造方法
{
//多态的引用
parent::__construct($name,$age);
$this->grade = $grade;
}
//编程2: 类属性的重载; $name是一个属性名称,并非是变量$name
public function __get($name)
{
if ($name == 'grade'){
return $name.'不允许查看';
}
return $this->$name;
}
public function __set($name,$value)
{
if ($name == 'grade'){
return $name.'不允许修改成绩';
}
$this->$name = $value;
}
//属性检测的重载方法 __isset 有返回值
public function __isset($name)
{
if ($name = 'grade'){
return false;
}
return isset($this->$name);
}
//__unset 无返回值
public function __unset($name)
{
if ($name == 'name' || $name == 'grade'){
return false;
}
unset($this->$name);
}
public function show(){
return ($this->name.'的年龄是:'.$this->age.',班级是:'.$this->grade);
}
}
//编程1:实例化类
$demo1 = new Student('小白',12,'三年级');
//$demo1->name = '小明';
//$demo1->age = 10;
//$demo1-> grade = '二年级';
//echo $demo1->name,'<br>';
//echo $demo1->age,'<br>';
//echo $demo1->grade,'<br>';
echo $demo1->show(),'<br>';
echo $demo1->getSex(),'<hr>';
echo $demo1::SITI_NAME,'<br>'; //:: 访问符
//编程4: 类中静态成员的访问
echo '静态成员的访问:'.$demo1::$static,'<br>';
echo '姓名:'.$demo1->name,'<br>';
echo '年龄:'.$demo1->age,'<br>';
echo '成绩:'.$demo1->grade;点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号