Inheritance and Interfaces
Inheritance lets a class extend another, reusing and specialising its behaviour, while interfaces define a contract of methods a class promises to implement.
Extending a Class
The extends keyword lets one class inherit another's public and protected properties and methods, and can override them with its own implementation.
class Animal {
public function __construct(protected string $name) {}
public function eat(): string {
return "{$this->name} is eating.";
}
}
class Dog extends Animal {
public function bark(): string {
return "{$this->name} says Woof!";
}
}
$d = new Dog("Rex");
echo $d->eat(); // inherited
echo $d->bark(); // defined in Dog
Interfaces
An interface declares method signatures without implementations. A class that implements an interface guarantees it provides those methods, letting different classes be used interchangeably wherever that interface is expected.
Common Mistakes
- Trying to instantiate an abstract class directly — abstract classes exist only to be extended.
- Forgetting to implement every method an interface requires, which causes a fatal error.
- Using inheritance to model a relationship that isn't truly "is-a", when composition would fit better.
- Assuming PHP supports multiple class inheritance — a class can only extend one parent, though it can implement multiple interfaces.
Professional Tip
A class can implement multiple interfaces even though it can only extend a single parent class. This is PHP's way of supporting flexible, multiple "contracts" without the complexity of true multiple inheritance.
Your Turn
Create an interface called Shape with a getArea() method, then implement it in two classes, Circle and Rectangle, each with their own area calculation.
Mini Quiz
How many classes can a single PHP class directly extend?