An abstract class defines a template that child classes must fill in. It cannot be instantiated directly.
abstract class Shape {
// Child classes must implement these
abstract public function area(): float;
abstract public function perimeter(): float;
// Shared implemented method
public function describe(): string {
return get_class($this)
. ": area=" . round($this->area(), 2)
. ", perimeter=" . round($this->perimeter(), 2);
}
}
class Rectangle extends Shape {
public function __construct(
private float $w,
private float $h
) {}
public function area(): float { return $this->w * $this->h; }
public function perimeter(): float { return 2 * ($this->w + $this->h); }
}
class Circle extends Shape {
public function __construct(private float $r) {}
public function area(): float { return M_PI * $this->r ** 2; }
public function perimeter(): float { return 2 * M_PI * $this->r; }
}
$shapes = [new Rectangle(5, 3), new Circle(4)];
foreach ($shapes as $shape) {
echo $shape->describe() . "<br>";
}
| Abstract Class | Interface | |
|---|---|---|
| Implemented methods | Yes | No (default methods: PHP 8) |
| Properties | Yes | Constants only |
| Constructor | Yes | No |
| Multiple | One parent | Many interfaces |