Abstract classes are incomplete blueprints with both regular and abstract methods. Child classes must implement all abstract methods. You cannot create an object directly from an abstract class — you must extend it first.
Abstract Classes
abstract class Shape {
abstract public function area(): float;
abstract public function perimeter(): float;
// Concrete method shared by all shapes
public function describe(): string {
return sprintf(
"%s — Area: %.2f, Perimeter: %.2f",
static::class,
$this->area(),
$this->perimeter()
);
}
}
class Circle extends Shape {
public function __construct(private float $radius) {}
public function area(): float {
return M_PI * $this->radius ** 2;
}
public function perimeter(): float {
return 2 * M_PI * $this->radius;
}
}
$c = new Circle(5);
echo $c->describe();
// Circle — Area: 78.54, Perimeter: 31.42