PHP Inheritance
Inheritance lets one class build on another, reusing its properties and methods while adding or changing behavior as needed.
What is inheritance?
Inheritance is a way to base a new class on an existing one. The class you inherit from is called the parent (or base) class, and the class that inherits is the child (or derived) class. The child automatically gains the parent's public and protected members and can add its own, so you avoid rewriting shared code.
In PHP you create this relationship with the extends keyword. A good rule of thumb is that inheritance should describe an 'is-a' relationship: a Dog is an Animal, a Manager is an Employee. If the relationship is really 'has-a', you usually want to store an object as a property instead.
Extending a base class
<?php
class Animal
{
public function __construct(public string $name)
{
}
public function describe(): string
{
return $this->name . " makes a sound.";
}
}
class Dog extends Animal
{
public function fetch(): string
{
return $this->name . " fetches the ball.";
}
}
$d = new Dog("Rex");
echo $d->describe(); // Rex makes a sound.
echo "\n";
echo $d->fetch(); // Rex fetches the ball.
?>Overriding methods
A child class can replace a method it inherited by declaring a method with the same name. This is called overriding, and it lets each subclass respond to the same method call in its own way. If you still want the parent's version to run as part of your new method, call it with the parent:: prefix.
Overriding and calling the parent
<?php
class Animal
{
public function __construct(public string $name)
{
}
public function describe(): string
{
return $this->name . " is an animal.";
}
}
class Cat extends Animal
{
public function describe(): string
{
return parent::describe() . " It says meow.";
}
}
$c = new Cat("Milo");
echo $c->describe(); // Milo is an animal. It says meow.
?>- Use extends to make one class inherit from another.
- A child inherits public and protected members but not private ones.
- Override an inherited method by redeclaring it with the same name.
- Call parent::methodName() to reuse the parent's version inside an override.
- PHP supports single inheritance only: a class can extend just one parent.
Preventing inheritance with final
Sometimes you want to stop a class from being extended, or stop a method from being overridden. The final keyword does exactly that. Marking a method final means subclasses must use it as-is, and marking a class final means no other class may extend it at all.
Using final
<?php
class PaymentGateway
{
final public function transactionId(): string
{
return "TXN-" . uniqid();
}
}
// A subclass may extend PaymentGateway but
// cannot override transactionId().
$gw = new PaymentGateway();
echo $gw->transactionId(); // e.g. TXN-64f2ab...
?>