批改状态:未批改
老师批语:
基本类:
<?php
/**
* 创建Cars类
*/
class Cars
{
protected $name;
protected $price;
//构造方法
public function __construct($name,$price)
{
$this->name = $name;
$this->price = $price;
}
public function run()
{
return '速度快';
}
}点击 "运行实例" 按钮查看在线实例
子类:
<?php
/*
* 创建电动汽车子类 ElectricCars
*/
class ElectricCars extends Cars
{
public function __get($name)
{
return $this->$name;
}
//1.对父类属性进行扩展,增加新的特征,如果不在子类中使用,推荐设置为private
private $camera = false; //是否有倒车影像
private $internet = false; //是否有上网功能
public function __construct($name,$price,$camera,$internet){
parent::__construct($name,$price);
$this->camera = $camera;
$this->internet = $internet;
}
//2.增加新的方法,扩展父类的功能
public function auto()
{
return '自动挡';
}
//3.将父类方法进行重写,就是功能重载,必须使用与父类一样的方法名
public function run()
{
// return '同时还能听歌,看视频';
//但更多的时候,我们并不会放弃原有功能,而只是在它上面进行追回而已
//那么,如何在子类中引用父类中的方法呢? 使用关键字: parent,后面跟上双冒号::
return parent::run().',同时还能上网,看视频';
}
}点击 "运行实例" 按钮查看在线实例
调用:
<?php
//类的自动加载
spl_autoload_register(function($name){
$path = __DIR__.'./class/'.$name.'.php';
if(file_exists($path)&&is_file($path)){
include "$path";
}
});
$a = new ElectricCars('BYD','269999',true,true);
echo '品牌:'.$a->name.'<br>';
echo '价格:'.$a->price.'元<br>';
echo '倒车影像:'.($a->camera?'支持':'没有').'<br>';
echo '车内上网:'.($a->internet?'支持':'没有').'<br>';
echo '特点:'.$a->auto().'<br>';
echo '好处:'.$a->run().'<br>';点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号