PHP 对象继承

phpserver side programmingprogramming更新于 2025/8/19 20:37:17

简介

继承是面向对象编程方法论中的一个重要原则。利用这一原则,可以定义两个类之间的关系。PHP 在其对象模型中支持继承。

PHP 使用 extends 关键字来建立两个类之间的关系。

语法

class B extends A

其中 A 是基类(也称为父类),B 称为子类或子类。子类继承父类的公共和受保护方法。子类可以重新定义或覆盖任何继承的方法。否则,继承的方法在与子类对象一起使用时,将保留其在父类中定义的功能。

父类的定义必须先于子类的定义。在这种情况下,脚本中 A 类的定义应该出现在 B 类的定义之前。

示例

<?php
class A{
   //A类的属性、常量和方法
}
class B extends A{
   //继承了公共和受保护的方法
}
?>

如果启用了自动加载,则通过加载类脚本获取父类的定义。

继承示例

以下代码显示子类继承了父类的公共和受保护成员

示例

<?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'

方法重写示例

如果从父类继承的方法在子类中重新定义,则新定义将覆盖先前的功能。以下示例中,public 方法在子类中再次定义

示例

<?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

相关文章