本文系統介紹抽象類、接口、instanceof 操作符、契約式編程,構建可擴展架構的基石。
abstractpublic function prototypeName($protoParam)
<?php
abstract class Car { abstract function getMaxSpeed(); }
class Roadster extends Car {
public $speed;
public function setSpeed($s=0){ $this->speed=$s; }
public function getMaxSpeed(){ return $this->speed; }
}
class Street {
public $cars=[]; public $limit;
public function __construct($l=200){ $this->limit=$l; }
protected function legal($car){ return $car->getMaxSpeed() < $this->limit; }
public function add($car){
if($this->legal($car)){ echo 'Allowed'; $this->cars[]=$car; }
else { echo 'Too fast'; }
}
}
$p=new Roadster(); $p->setSpeed(340);
$s=new Street(80); $s->add($p); // Too fast
?>
interface 定義,所有方法隱式 publicimplements 實現,可多實現I 開頭abstract class Car { abstract function setSpeed($s=0); }
interface ISpeedInfo { function getMaxSpeed(); }
class Roadster extends Car implements ISpeedInfo {
public $speed;
public function setSpeed($s=0){ $this->speed=$s; }
public function getMaxSpeed(){ return $this->speed; }
}
$p = new Roadster(); echo $p instanceof Car; // 1 echo $p instanceof ISpeedInfo; // 1
檢測:具體類型、繼承鏈、接口實現。
先定接口 (契約),後寫實現。如建築師先畫藍圖。優勢:封裝、並行開發、可測試。
| 抽象類 | 接口 | |
|---|---|---|
| 關鍵字 | abstract | interface |
| 方法體 | 可有非抽象方法 | 全無 |
| 繼承 | extends (單) | implements (多) |
| 屬性 | 可定義 | 不可 (僅常量) |
| 訪問級別 | 任意 | 必須 public |
PHP 無多重繼承,但「單繼承 + 多接口」完美替代。契約式編程落地架構,是高質量 PHP 開發的基石。