继承是面向对象的一个重要概念,通过使用继承可以重用已有类的属性和方法。被继承的类叫做父类,获得继承权的类称为子类。
1.继承一个类
例:extends.php
class Fruit{ //创建一个Fruit类
}
class Apple extends Fruit{ //创建一个Apple类 继承父类Fruit
public function __construct(){ //公有 构造函数
echo 'This is apple.
'; //打印This is apple.
}
}
class Banana extends Fruit{//创建一个Banana类 继承父类Fruit
public function __construct(){//公有 构造函数
echo 'This is banana.
';//打印This is banana.
}
}
class Orange extends Fruit{//创建一个Orange类 继承父类Fruit
public function __construct(){//公有 构造函数
echo 'This is orange.
';//打印This is orange.
}
}
$apple = new Apple();
$banana = new Banana();
$orange = new Orange();
?>
结果:
PHP的构造函数也是可以被继承的,我们给 Fruit类添加一个构造函数。
例:extends2.php
class Fruit{//创建一个Fruit类
public function __construct(){//公有 构造函数
echo 'This is fruit.
';//打印This is fruit.
}
}
class Apple extends Fruit{//创建一个Apple类 继承父类Fruit
}
class Banana extends Fruit{//创建一个Banana类 继承父类Fruit
}
class Orange extends Fruit{//创建一个Orange类 继承父类Fruit
}
$apple = new Apple();//实例化
$banana = new Banana();//实例化
$orange = new Orange();//实例化
?>
结果:
注:PHP中一个类只能继承一个父类,我们称为单继承。
2.public、protected、private在继承类中的作用
public、protected关键词定义的成员变量和成员函数可以被子类继承。Private则不行。
例:extends_access.php
class Fruit{//创建Fruit类
protected $color; //保护可以被继承 成员变量 $color
private $shape = 'unknow'; //私有无法继承 成员变量 $shape
public function __construct(){ //公有 构造函数
echo 'This is fruit.
'; //打印This is fruit.
}
}
class Apple extends Fruit{ //创建Apple类 继承父类Fruit
public function __construct(){ //公有 构造函数
$this->color = 'red'; //继承父类成员变量 color
echo $this->shape; //无法继承 报错 变量未定义
echo 'This is apple.
'; //打印This is apple.
}
}
class Banana extends Fruit{//创建Banana类 继承父类Fruit
public function __construct(){//公有 构造函数
$this->color = 'yelow';//继承父类成员变量 color
echo 'This is banana.
';//打印This is banana.
}
}
class Orange extends Fruit{//创建Orange 类 继承父类Fruit
public function __construct(){//公有 构造函数
$this->color = 'green';//继承父类成员变量 color
echo 'This is orange.
';//打印This is orange.
}
}
$apple = new Apple();//实例化
$banana = new Banana();//实例化
$orange = new Orange();//实例化
?>
结果:
3.final在继承类中的影响
如果不希望被继承,在该类前面加final关键词。
例:final.php
final class Super{//创建Super类(最终类)
public function show() { //公有 成员函数 show
echo "BaseClass::show()"; //打印BaseClass::show()
}
}
class Sub extends Super {//创建Sub无法继承父类Super
}
?>
结果:
希望一个类的方法不被子类继承。
例:final2.php
class Super{ //创建Super类
final public function show() { //公有 成员函数 show 无法被继承
echo "Super::show()"; //打印Super::show()
}
}
class Sub extends Super { //创建Sub继承父类Super
public function show() {//公有 成员函数 show
echo "Sub:: show()";//打印Sub:: show()
}
}
?>
结果:
请大家多多关注!谢谢,此文只供学习之用。