PHP对象继承

介绍

继承是面向对象编程方法的重要原理。使用此原理,可以定义两个类之间的关系。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