批改状态:合格
老师批语:
写一个父类与子类,
在子类中扩展父类的属性,并重载父类的方法,分享代码如下:
父类代码:
<?php
//创建父类
class XiaoMingParent
{
protected $name;
protected $age;
protected $profession;
public function __construct($name,$age,$profession)
{
$this->name = $name;
$this->age = $age;
$this->profession = $profession;
}
public function hobby()
{
return '钓鱼。';
}
}点击 "运行实例" 按钮查看在线实例
子类代码:
<?php
//创建子类
class XiaoMing extends XiaoMingParent
{
//创建查询器,实现外部访问父类属性
public function __get($name)
{
return $this->$name;
}
//新增子类属性
private $education;
//创建构造方法
public function __construct($name,$age,$profession,$education)
{
//调用父类构造器初始化父类属性
parent::__construct($name,$age,$profession);
//初始化子类新属性
$this->education = $education;
}
//重载
public function hobby()
{
return '打游戏。';
}
}点击 "运行实例" 按钮查看在线实例
调用代码:
<?php
//调用子类
//使用自动加载器来加载类:
spl_autoload_register(function($className){
require './class/'.$className.'.php';
});
$son = new XiaoMing('小明', 25, '程序猿', '大学本科');
echo '姓名:'.$son->name.'<br>';
echo '年龄:'.$son->age.'<br>';
echo '职业:'.$son->profession.'<br>';
echo '学历:'.$son->education.'<br>';
echo '爱好:'.$son->hobby();点击 "运行实例" 按钮查看在线实例
运行效果:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号