介绍
继承是面向对象编程方法的重要原理。使用此原理,可以定义两个类之间的关系。PHP在其对象模型中支持继承。
PHP使用extends关键字在两个类之间建立关系。
语法
class B extends A
其中A是基类(也称为父类),B是子类或子类。子类继承父类的公共方法和受保护的方法。子类可以重新定义或覆盖任何继承的方法。如果不是这样,当与子类的对象一起使用时,继承的方法将保留其父类中定义的功能。
父类的定义必须在子类的定义之前。在这种情况下,脚本中的类B的定义应出现在类A的定义之前。
示例
<?php class A{ //A类的属性,常量和方法 } class B extends A{ //继承公共和受保护的方法 } ?>
如果启用了自动加载,则通过加载类脚本来获取父类的定义。
继承实例
以下代码显示子类继承父类的公共成员和受保护成员
示例
<?php class parentclass{ public function publicmethod(){ echo "This is public method of parent class\n" ; } protected function protectedmethod(){ echo "This is protected method of parent class\n" ; } private function privatemethod(){ echo "This is private method of parent class\n" ; } } class childclass extends parentclass{ public function childmethod(){ $this->protectedmethod(); //$this->privatemethod(); //this will produce error } } $obj=new childclass(); $obj->publicmethod(); $obj->childmethod(); ?>
输出结果
这将产生以下结果。-
This is public method of parent class This is protected method of parent class PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context 'childclass'
方法覆盖示例
如果在子类中重新定义了从父类继承的方法,则新定义将覆盖以前的功能。在下面的示例中,在子类中再次定义了publicmethod
示例
<?php class parentclass{ public function publicmethod(){ echo "This is public method of parent class\n" ; } protected function protectedmethod(){ echo "This is protected method of parent class\n" ; } private function privatemethod(){ echo "This is private method of parent class\n" ; } } class childclass extends parentclass{ public function publicmethod(){ echo "public method of parent class is overridden in child class\n" ; } } $obj=new childclass(); $obj->publicmethod(); ?>
输出结果
这将产生以下结果。-
public method of parent class is overridden in child class
继承继承
PHP不支持多重继承。因此,一个类不能扩展两个或多个类。但是,它支持分层继承,如下所示:
示例
<?php class A{ function test(){ echo "method in A class"; } } class B extends A{ // } class C extends B{ // } $obj=new C(); $obj->test(); ?>
输出结果
这将显示以下结果
method in A class
热门文章
- 「2月18日」最高速度19M/S,2025年SSR/Clash/Shadowrocket/V2ray每天更新免费节点订阅链接
- 深圳宠物领养中心 免费政策 深圳宠物领养中心 免费政策最新
- 天宠宠物医院怎么样啊(天宠官网)
- 「2月15日」最高速度19.5M/S,2025年V2ray/SSR/Shadowrocket/Clash每天更新免费节点订阅链接
- 动物疫苗厂家有多少家上市公司 动物疫苗厂家有多少家上市公司呢
- 「3月3日」最高速度21.4M/S,2025年Shadowrocket/Clash/V2ray/SSR每天更新免费节点订阅链接
- 动物疫苗价格一览表图片高清大图下载(动物疫苗价格一览表图片高清大图下载)
- 如果我们将时间分量和日期分量作为DATEDIFF()函数的参数包括在内,MySQL将返回什么?
- Oracle模糊查询,不区分大小写
- 1970年6月27日农历是多少(1970年阳历6月26号阴历是多少)