PHP Abstract Classes
An abstract class is a class that is only meant to be a parent. You cannot create objects from it directly; instead, child classes extend it and fill in the missing pieces. It is declared with the abstract keyword.
An abstract class can contain abstract methods — method signatures without a body. Every non-abstract child class must implement them. This lets the parent define what every subclass can do while leaving how to each subclass.
A first abstract class
<?php
abstract class Shape {
public function __construct(protected string $name) {}
abstract public function area(): float;
// A normal method that uses the abstract one
public function describe(): string {
return sprintf('%s with area %.2f', $this->name, $this->area());
}
}
class Rectangle extends Shape {
public function __construct(private float $w, private float $h) {
parent::__construct('Rectangle');
}
public function area(): float { return $this->w * $this->h; }
}
class Triangle extends Shape {
public function __construct(private float $base, private float $height) {
parent::__construct('Triangle');
}
public function area(): float { return $this->base * $this->height / 2; }
}
$shapes = [new Rectangle(4, 2.5), new Triangle(6, 3)];
foreach ($shapes as $s) {
echo $s->describe() . "\n";
}Rectangle with area 10.00
Triangle with area 9.00
describe() is written once in Shape, yet works for every shape because it calls area(), which each child implements. This pattern is called the template method.
You cannot instantiate an abstract class
<?php
abstract class Payment {
abstract public function pay(float $amount): string;
}
try {
$p = new Payment();
} catch (Error $e) {
echo "Error: " . $e->getMessage() . "\n";
}
$anonymous = new class extends Payment {
public function pay(float $amount): string {
return "Paid {$amount} in cash";
}
};
echo $anonymous->pay(12.5) . "\n";
var_dump($anonymous instanceof Payment);Error: Cannot instantiate abstract class Payment
Paid 12.5 in cash
bool(true)
The second half shows an anonymous class: a one-off class defined right where you create the object. It is handy in tests or when you need a quick implementation.
Rules for abstract methods
| Rule | Detail |
|---|---|
| Class must be abstract | Any class with at least one abstract method must itself be declared abstract |
| No body | abstract public function area(): float; ends with a semicolon |
| Children must implement | A non-abstract child must implement every inherited abstract method |
| Compatible signature | The implementation needs a compatible signature (same or wider parameters, same or narrower return type) |
| Visibility | The implementation must have the same or a wider visibility |
| Partial implementation | A child that is still abstract may leave some methods unimplemented |
If a concrete class forgets to implement an abstract method, PHP stops with a fatal error before running any code, so you find the mistake immediately.
A realistic example: exporters
Abstract classes shine when subclasses share a lot of code and differ in a few steps. Here every exporter shares the row-looping logic, and each format only defines how to write the header and a row:
<?php
abstract class Exporter {
public function export(array $rows): string {
$out = $this->header(array_keys($rows[0]));
foreach ($rows as $row) {
$out .= $this->row($row);
}
return $out;
}
abstract protected function header(array $columns): string;
abstract protected function row(array $values): string;
}
class CsvExporter extends Exporter {
protected function header(array $columns): string {
return implode(',', $columns) . "\n";
}
protected function row(array $values): string {
return implode(',', $values) . "\n";
}
}
class MarkdownExporter extends Exporter {
protected function header(array $columns): string {
return '| ' . implode(' | ', $columns) . " |\n"
. '|' . str_repeat('---|', count($columns)) . "\n";
}
protected function row(array $values): string {
return '| ' . implode(' | ', $values) . " |\n";
}
}
$data = [
['item' => 'Pen', 'qty' => 3],
['item' => 'Ruler', 'qty' => 1],
];
echo (new CsvExporter())->export($data);
echo "\n";
echo (new MarkdownExporter())->export($data);item,qty
Pen,3
Ruler,1
| item | qty |
|---|---|
| Pen | 3 |
| Ruler | 1 |
Adding a JSON or HTML exporter later only means writing two small methods.
Abstract class or interface?
| Abstract class | Interface |
|---|---|
| Can hold properties and implemented methods | Only method signatures and constants |
| Can have a constructor | No constructor logic |
| A class extends only one | A class can implement many |
| Good for sharing code between closely related classes | Good for describing a capability shared by unrelated classes |
Often you use both: an interface describes the contract, and an abstract base class provides a convenient partial implementation of it.
Tip: Keep abstract methods
protectedwhen they are steps used internally by the parent (likeheader()androw()above). Outside code then only sees the publicexport()method.
Test yourself
What happens when you run new Shape() where Shape is abstract?
- An empty Shape object is created
- An
Erroris thrown: cannot instantiate abstract class - PHP returns null
- The first subclass is created instead
Which statement about abstract methods is true?
- They must have a body
- They can only appear in interfaces
- A concrete child class must implement them
- They are always private
How many abstract classes can a single PHP class extend?
- One
- Two
- Any number
- None — abstract classes can't be extended