创建父类和子类,子类加载父类:
父类代码:
实例
/**
* 创建手机类:MobilePhone
*/
class MobilePhone
{
// public $brand;
protected $brand;
protected $model;
// private $price;
protected $price;
//构造方法
public function __construct($brand,$model,$price)
{
$this->brand = $brand;
$this->model = $model;
$this->price = $price;
}
public function call()
{
return '打电话';
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
创建子类:
实例
class SmartPhone extends MobilePhone
{
//1.无需任何代码,父类MobilePhone中的所有公共和受保护的成员,在当前类中可以直接访问
//创建查询器,实现了外部访问
public function __get($name)
{
return $this->$name;
}
//1.对父类属性进行扩展,增加新的特征,如果不在子类中使用,推荐设置为private
private $camera = false; //是否有照相功能
private $internet = false; //是否有上网功能
//必须使用构造方法对使用当前新增属性生效
public function __construct($brand,$model,$price,$camera,$internet)
{
// $this->brand = $brand;
// $this->model = $model;
// $this->price = $price;
/**
* 你可能发现了,这上面的三行属性初始化语句,与父类构造器的语句完全一致
* 所以,我们完全可以直接调用父类的构造器来简化子类的构造器
*/
//调用父类构造器初始化类属性
parent::__construct($brand, $model, $price);//一行顶三行
$this->camera = $camera;
$this->internet = $internet;
}
//2.增加新的方法,扩展父类的功能
public function game()
{
return '玩游戏';
}
//3.将父类方法进行重写,就是功能重载,必须使用与父类一样的方法名:call()
public function call()
{
// return '同时还能听歌,看视频';
//此时,访问call()将会输出子类定义的功能
//但更多的时候,我们并不会放弃原有功能,而只是在它上面进行追回而已
//那么,如何在子类中引用父类中的方法呢? 使用关键字: parent,后面跟上双冒号::
return parent::call().',同时还能听歌,看视频';
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例