PHP Abstract Classes

PHP Abstract Classes

An abstract class defines a template that child classes must fill in. It cannot be instantiated directly.

1 - Defining

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);
    }
}

2 - Implementing

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>";
}

3 - Abstract vs Interface

Abstract ClassInterface
Implemented methodsYesNo (default methods: PHP 8)
PropertiesYesConstants only
ConstructorYesNo
MultipleOne parentMany interfaces

Note: Use an abstract class when subclasses share common logic or state. Use an interface when you only want to enforce a contract across unrelated classes.

-Tip-