PHP – 抽象類



PHP 的保留字列表包括“abstract”關鍵字。當一個類用“abstract”關鍵字定義時,它不能被例項化,即你不能宣告此類的新物件。抽象類可以被另一個類擴充套件。

abstract class myclass {
   // class body
}

如上所述,你**不能宣告此類的物件**。因此,以下語句 -

$obj = new myclass;

將導致如下所示的**錯誤**訊息 -

PHP Fatal error:  Uncaught Error: Cannot instantiate abstract class myclass

抽象類可能包含屬性、常量或方法。類成員可以是公有、私有或受保護型別。類中的一種或多種方法也可以定義為抽象方法。

如果類中的任何方法是抽象的,那麼該類本身必須是抽象類。換句話說,普通類不能在其內部定義抽象方法。

這將引發**錯誤** -

class myclass {
   abstract function myabsmethod($arg1, $arg2);
   function mymethod() #this is a normal method {
      echo "Hello";
   }
}

**錯誤訊息**將顯示為 -

PHP Fatal error:  Class myclass contains 1 abstract method 
and must therefore be declared abstract

你可以使用抽象類作為父類並用子類擴充套件它。但是,子類必須為父類中的每個抽象方法提供具體的實現,否則將遇到錯誤。

示例

在以下程式碼中,**myclass** 是一個**抽象類**,**myabsmethod()** 是一個**抽象方法**。它的派生類是**mynewclass**,但它沒有在其父類中實現抽象方法。

<?php
   abstract class myclass {
      abstract function myabsmethod($arg1, $arg2);
      function mymethod() {
         echo "Hello";
      }
   }
   class newclass extends myclass {
      function newmethod() {
         echo "World";
      }
   }
   $m1 = new newclass;
   $m1->mymethod();
?>

在這種情況下,**錯誤訊息**為 -

PHP Fatal error:  Class newclass contains 1 abstract method and must 
therefore be declared abstract or implement the remaining 
methods (myclass::myabsmethod) 

它表明 newclass 應該實現抽象方法,或者它應該被宣告為抽象類。

示例

在以下 PHP 指令碼中,我們有**marks** 作為抽象類,其中 percent() 是一個抽象方法。另一個**student** 類擴充套件了**marks** 類並實現了它的 percent() 方法。

<?php
   abstract class marks {
      protected int $m1, $m2, $m3;
      abstract public function percent(): float;
   }

   class student extends marks {
      public function __construct($x, $y, $z) {
         $this->m1 = $x;
         $this->m2 = $y;
         $this->m3 = $z;
      }
      public function percent(): float {
         return ($this->m1+$this->m2+$this->m3)*100/300;
      }
   }

   $s1 = new student(50, 60, 70);
   echo "Percentage of marks: ". $s1->percent() . PHP_EOL;
?>

它將產生以下**輸出** -

Percentage of marks: 60

PHP 中介面和抽象類的區別

PHP 中抽象類的概念與介面非常相似。但是,介面和抽象類之間存在一些區別。

抽象類

介面

使用 abstract 關鍵字定義抽象類

使用 interface 關鍵字定義介面

抽象類不能被例項化

介面不能被例項化。

抽象類可以具有普通方法和抽象方法

介面必須僅宣告帶引數和返回型別的方法,而不能帶任何主體。

抽象類被子類擴充套件,子類必須實現所有抽象方法

介面必須由另一個類實現,該類必須提供介面中所有方法的功能。

可以具有公有、私有或受保護的屬性

介面中不能宣告屬性

廣告