PHP 物件介面


簡介

介面是面向物件程式設計的一個重要特性,它允許指定類需要實現的方法,而無需定義這些方法的具體實現方式。

PHP 透過 **interface** 關鍵字支援介面。介面類似於類,但其方法沒有定義方法體。介面中的方法必須是 public 的。實現這些方法的繼承類必須使用 **implements** 關鍵字而不是 extends 關鍵字進行定義,並且必須提供父介面中所有方法的實現。

語法

<?php
interface testinterface{
   public function testmethod();
}
class testclass implements testinterface{
   public function testmethod(){
      echo "implements interfce method";
   }
}
?>

實現類必須定義介面中的所有方法,否則 PHP 解析器會丟擲異常。

示例

 線上演示

<?php
interface testinterface{
   public function test1();
   public function test2();
}
class testclass implements testinterface{
   public function test1(){
      echo "implements interface method";
   }
}
$obj=new testclass()
?>

輸出

錯誤如下所示:

PHP Fatal error: Class testclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testinterface::test2)

可擴充套件介面

與普通類一樣,介面也可以使用 **extends** 關鍵字進行繼承。

在下面的示例中,父類有兩個抽象方法,子類只重定義了其中一個。這會導致如下錯誤:

示例

<?php
interface testinterface{
   public function test1();
}
interface myinterface extends testinterface{
   public function test2();
}
class testclass implements myinterface{
   public function test1(){
      echo "implements test1 method";
   }
   public function test2(){
      echo "implements test2 method";
   }
}
?>

使用介面實現多重繼承

PHP 不允許在 extends 子句中使用多個類。但是,可以透過讓子類實現一個或多個介面來實現多重繼承。

在下面的示例中, MyClass 擴充套件了 TestClass 並實現了 TestInterface 以實現多重繼承。

示例

 線上演示

<?php
interface testinterface{
   public function test1();
}
class testclass{
   public function test2(){
      echo "this is test2 function in parent class
";    } } class myclass extends testclass implements testinterface{    public function test1(){       echo "implements test1 method
";    } } $obj=new myclass(); $obj->test1(); $obj->test2(); ?>

輸出

這將產生以下輸出:

implements test1 method
this is test2 function in parent class

介面示例

示例

 線上演示

<?php
interface shape{
   public function area();
}
class circle implements shape{
   private $rad;
   public function __construct(){
      $this->rad=5;
   }
   public function area(){
      echo "area of circle=" . M_PI*pow($this->rad,2) ."
";    } } class rectangle implements shape{    private $width;    private $height;    public function __construct(){       $this->width=20;       $this->height=10;    }    public function area(){       echo "area of rectangle=" . $this->width*$this->height ."
";    } } $c=new circle(); $c->area(); $r=new rectangle(); $r->area(); ?>

輸出

以上指令碼產生以下結果

area of circle=78.539816339745
area of rectangle=200

更新於: 2020-09-18

587 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.