PHP OOP - 继承
PHP - 什么是继承?
OOP 中的继承 = 当一个类从另一个类派生时。
子类将继承父类的所有公共和受保护属性及方法。此外,它还可以有自己的属性和方法。
请使用 extends
关键字定义继承的类。
让我们看一个例子:
实例
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color; } public function intro() { echo "这种水果是{$this->name},颜色是{$this->color}。"; } } // Strawberry 继承自 Fruit class Strawberry extends Fruit { public function message() { echo "我是水果还是浆果?"; } } $strawberry = new Strawberry("草莓", "红色"); $strawberry->message(); $strawberry->intro(); ?>
例子解释
Strawberry
类继承自 Fruit
类。
这意味着 Strawberry
类可以使用 Fruit
类中的公共属性 $name
和 $color
以及公共方法 __construct()
和 intro()
,这是因为继承。
Strawberry
类也有自己的方法:message()
。
PHP - 继承和受保护的访问修饰符
在上一章中,我们了解到受保护的属性或方法可以在类内部以及从该类派生的类中被访问。那是什么意思?
让我们看一个例子:
实例
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color; } protected function intro() { echo "这种水果是{$this->name},颜色是{$this->color}。"; } } class Strawberry extends Fruit { public function message() { echo "我是水果还是浆果?"; } } // 尝试从类外部调用所有三个方法 $strawberry = new Strawberry("Strawberry", "red"); // 没问题。__construct() 是公共的。 $strawberry->message(); // 没问题。message() 是公共的。 $strawberry->intro(); // 错误。intro()是受保护的 ?>
在上面的例子中,我们看到如果我们尝试从类外部调用一个受保护的方法(intro()
),将会收到一个错误。公共方法将正常工作!
让我们再看一个例子:
实例
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color; } protected function intro() { echo "这种水果是{$this->name},颜色是{$this->color}。"; } } class Strawberry extends Fruit { public function message() { echo "我是水果还是浆果?"; // 从派生类内部调用受保护的方法 - 没问题 $this -> intro(); } } $strawberry = new Strawberry("Strawberry", "red"); // 没问题。__construct() 是公共的。 $strawberry->message(); // 没问题。message()是公共的,并且它从派生类内部调用了intro()(它是受保护的)。 ?>
在上面的示例中,我们看到一切正常!这是因为我们从派生类内部调用了受保护的方法(intro()
)。
PHP - 重写继承的方法
继承的方法可以通过在子类中重新定义(使用相同的名称)来重写。
实例
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color; } public function intro() { echo "这种水果是{$this->name},颜色是{$this->color}。"; } } class Strawberry extends Fruit { public $weight; public function __construct($name, $color, $weight) { $this->name = $name; $this->color = $color; $this->weight = $weight; } public function intro() { echo "这种水果是{$this->name},颜色是{$this->color},重量是{$this->weight}克。"; } } $strawberry = new Strawberry("草莓", "红色", 50); $strawberry->intro(); ?>
PHP - final 关键字
final
关键字可用于防止类继承或防止方法重写。
下例展示了如何防止类继承:
实例
<?php final class Fruit { // 一些代码 } // 将导致错误 class Strawberry extends Fruit { // 一些代码 } ?>
下例展示了如何防止方法重写:
实例
<?php class Fruit { final public function intro() { // 一些代码 } } class Strawberry extends Fruit { // will result in error public function intro() { // 一些代码 } } ?>