PHP 对象继承
简介
继承是面向对象编程方法学的一个重要原则。使用这个原则,可以定义两个类之间的关系。PHP在其对象模型中支持继承。
PHP 使用 **extends** 关键字来建立两个类之间的关系。
语法
class B extends A
其中 A 是基类(也称为父类),B 被称为子类或派生类。子类继承父类的公有和受保护方法。子类可以重新定义或覆盖任何继承的方法。如果没有,则在使用子类对象时,继承的方法将保留其在父类中定义的功能。
父类的定义必须在子类定义之前。在这种情况下,类 A 的定义应该在脚本中类 B 的定义之前出现。
示例
<?php
class A{
//properties, constants and methods of class A
}
class B extends A{
//public and protected methods inherited
}
?>如果启用了自动加载,则通过加载类脚本获取父类的定义。
继承示例
下面的代码显示子类继承父类的公有和受保护成员
示例
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class
" ;
}
protected function protectedmethod(){
echo "This is protected method of parent class
" ;
}
private function privatemethod(){
echo "This is private method of parent class
" ;
}
}
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
" ;
}
protected function protectedmethod(){
echo "This is protected method of parent class
" ;
}
private function privatemethod(){
echo "This is private method of parent class
" ;
}
}
class childclass extends parentclass{
public function publicmethod(){
echo "public method of parent class is overridden in child class
" ;
}
}
$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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP