Correction status:Uncorrected
Teacher's comments:
父类代码:
<?php /** * Created by PhpStorm. */ class Computer { protected $brand; protected $model; protected $price; //构造方法 public function __construct($brand,$model,$price) { $this->brand=$brand; $this->model=$model; $this->price=$price; } public function internet(){ return '上网'; } }
点击 "运行实例" 按钮查看在线实例
子类代码:
<?php class SuperBook extends Computer { //创建查询器,实现了外部访问 public function __get($name) { return $this-> $name; } //1.对父类属性进行扩展,增加新的特征,如果不在子类中使用,推荐设置为private private $camera = false; //是否有照相功能 private $game = false; //是否有游戏功能 //必须使用构造方法对使用当前新增属性生效 public function __construct($brand, $model, $price,$camera,$game) { //调用父类构造器初始化类属性 parent::__construct($brand, $model, $price); $this->camera = $camera; $this->game = $game; } //2.增加新的方法,扩展父类的功能 public function study() { return '学习'; } //3.将父类方法进行重写,就是功能重载,必须使用与父类一样的方法名 public function internet(){ return parent::internet().'同时还能看电影、写程序'; } }
点击 "运行实例" 按钮查看在线实例
测试代码:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/5/5 * Time: 11:50 */ //使用自动加载器来加载类:(简写版) spl_autoload_register(function ($className){ require './class/'.$className.'.php'; }); $superbook = new SuperBook('联想','Y480','4899',true,true); //换一组数据来初始化对象,验证parent::__contrunctor() $superbook = new SuperBook('THINK','L440','5899',true,true); echo '品牌:'.$superbook->brand.'</br>'; echo '型号:'.$superbook->model.'</br>'; echo '价格:'.$superbook->price.'</br>'; echo '照相:'.($superbook->camera?'支持':'没有').'</br>'; echo '游戏:'.($superbook->camera?'支持':'没有').'</br>'; echo $superbook->internet();
点击 "运行实例" 按钮查看在线实例
效果图: