批改状态:合格
老师批语:
主题:
写一个父类与子类,在子类中扩展父类的属性,并重载父类的方法。
执行结果:

<?php
/*
* 基类/父类(汽车)
*/
class Car {
//public(公共),private(私有),protected(受保护)
protected $cnum;
protected $color;
protected $style;
//构造方法
public function __construct($cnum, $color, $style) {
$this->cnum = $cnum;
$this->color = $color;
$this->style = $style;
}
//一般方法
public function drive() {
return '开车';
}
}点击 "运行实例" 按钮查看在线实例
<?php
/*
* SmallCar:小车类
* 子类/派生类
*/
class SmallCar extends Car {
//创建查询器,访问受保护属性
public function __get($name)
{
return $this->$name;
}
//扩展父类,增加功能,属性都为私有(private)
private $skylight = false; //天窗
private $turbo = false; //涡轮增压
//用构造器构造方法
public function __construct($cnum, $color, $style, $skylight, $turbo) {
//初始化属性
//$this->num = $cnum;
//$this->color = $color;
//$this->style = $style;
//继承方式初始化属性
parent::__construct($cnum, $color, $style);
//子类中新增的属性不能使用继承方式初始化
$this->skylight= ($skylight) ? '有' : '无';
$this->turbo= ($turbo) ? '有' : '无';
}
//增加小车新功能
public function play() {
return '媒体功能';
}
public function fly() {
//继承父类方法
return parent::drive(). '飞翔';
}
}点击 "运行实例" 按钮查看在线实例
<?php
/*
* 类的继承与方法重载
*/
//使用自动加载器加载类(加载父类,子类自动继承)
spl_autoload_register(function($ClassName) {
require './class/'. $ClassName. '.php';
});
//实例化对象
$smallCar = new SmallCar('鄂A88888', '白色', '法拉利', true, false);
//父类中的属性
echo '车牌号码:'. $smallCar->cnum. '<br>';
echo '车辆颜色:'. $smallCar->color. '<br>';
echo '车牌型号:'. $smallCar->style. '<br>';
//子类中新增的属性
echo '天窗:'. $smallCar->skylight. '<br>';
echo '涡轮增压:'. $smallCar->turbo. '<br>';
//子类中定义的方法
echo '功能:'. $smallCar->play(). '<br>';
echo '特点:'. $smallCar->fly(). '<br>';点击 "运行实例" 按钮查看在线实例
总结:
使用自动加载器加载类(加载父类,子类自动继承):spl_autoload_register()。
子类继承使用extends关键字,可以直接使用继承方式parent::__construct()方式初始化,子类新增的属性不能使用继承方式初始化,重载父类方法使用parent::
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号