抽象方法無方法體,僅作為子類實現的佔位符。包含抽象方法的類必須宣告為 abstract,不可實例化,需繼承並實現所有抽象方法後才能實例化。
abstract 關鍵字純抽象類(僅含抽象方法)可用 interface + implements 替代:
interface MyInterface { ... }
class MyClass implements MyInterface { ... }
兩種風格依團隊偏好選擇。
<?php
abstract class Shape { abstract function getArea(); }
abstract class Polygon extends Shape { abstract function getNumberOfSides(); }
class Triangle extends Polygon {
public $base; public $height;
public function getArea() { return ($this->base * $this->height) / 2; }
public function getNumberOfSides() { return 3; }
}
class Rectangle extends Polygon {
public $width; public $height;
public function getArea() { return $this->width * $this->height; }
public function getNumberOfSides() { return 4; }
}
class Circle extends Shape {
public $radius;
public function getArea() { return pi() * $this->radius * $this->radius; }
}
// 多態集合處理
$shapes = [new Triangle(4,5), new Rectangle(5,7), new Circle(3)];
foreach ($shapes as $s) {
if ($s instanceof Shape) print "Area: " . $s->getArea() . "<br>";
if ($s instanceof Polygon) print "Sides: " . $s->getNumberOfSides() . "<br>";
}
?>
instanceof 運算符用於運行期類型檢查,配合抽象介面實現開閉原則。