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
廣告