iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Abstract Classes

An abstract class can't be instantiated directly — only inherited. It can declare abstract methods that subclasses must implement.

The shape

PHP
abstract class Shape {
    abstract public function area(): float;

    public function describe(): string {
        return sprintf('area=%.2f', $this->area());
    }
}

class Circle extends Shape {
    public function __construct(public float $r) {}
    public function area(): float {
        return M_PI * $this->r ** 2;
    }
}

class Rectangle extends Shape {
    public function __construct(public float $w, public float $h) {}
    public function area(): float {
        return $this->w * $this->h;
    }
}

echo (new Circle(5))->describe();      // area=78.54
echo (new Rectangle(3, 4))->describe(); // area=12.00

// new Shape();   // Error — cannot instantiate abstract class

Rules

  • An abstract method has no body — just signature.
  • Any class with at least one abstract method must itself be declared abstract.
  • Subclasses must implement every abstract method (or stay abstract themselves).
  • Subclass signatures must be covariant — same or more specific.

Abstract class vs interface

Abstract classInterface
Can hold state (properties).No properties (except const).
Can have implemented methods + abstract ones.Methods are all unimplemented (default methods coming).
Single inheritance only.A class can implement many.
"Is-a" with shared behaviour."Can-do" — a capability contract.
Tip: When in doubt, start with an interface. Promote to abstract class only when you find concrete shared code that several subclasses need.

Example

Example
<?php
abstract class Shape {
    abstract public function area(): float;
    public function describe(): string {
        return sprintf('area=%.2f', $this->area());
    }
}
class Circle extends Shape {
    public function __construct(public float $r) {}
    public function area(): float { return M_PI * $this->r ** 2; }
}
echo (new Circle(5))->describe();
Try it Yourself »

Exercise

Cannot-instantiate keyword.

class Shape {}

Test yourself

Q1. Abstract methods…
Q2. Abstract class can hold…
Q3. Abstract class vs interface — abstract can also…

Discussion

Loading…