Skip to content

PHP Tutorial Advanced OOP

Inheritance

Lesson 211 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Inheritance lets one class build on another. The new class (the child) gets everything from the existing class (the parent) and can add more.

index.php
PHP
<?php
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!";
    }
}

$dog = new Dog("Bruno");

echo $dog->eat() . "\n";
echo $dog->bark();
Output
OUTPUT
Bruno is eating.
Bruno says woof!

Dog did not write eat() or the constructor. It inherited them from Animal, and it added bark().

What is inherited

  • All public and protected properties and methods.
  • The constructor (if the child does not write its own).

Private members belong to the parent only. The child cannot use them.

The “is a” test

Inheritance fits when the child is a kind of the parent: a Dog is an Animal. If you would say “has a” (a Car has an Engine), use composition instead. See Composition vs Inheritance.

A child can add its own constructor

Call the parent constructor with parent::__construct().

index.php
PHP
<?php
class Vehicle
{
    public function __construct(protected string $brand) {}
}

class Car extends Vehicle
{
    public function __construct(string $brand, private int $doors)
    {
        parent::__construct($brand);
    }

    public function describe(): string
    {
        return "{$this->brand} with {$this->doors} doors";
    }
}

echo (new Car("Tata", 4))->describe();
Output
OUTPUT
Tata with 4 doors

Check the relationship

index.php
PHP
<?php
class Animal {}
class Dog extends Animal {}

$dog = new Dog();

var_dump($dog instanceof Dog);
var_dump($dog instanceof Animal);
echo get_parent_class($dog);
Output
OUTPUT
bool(true)
bool(true)
Animal

A Dog can be used anywhere an Animal is expected.

One parent only

A PHP class can extend only one parent. For sharing code across unrelated classes, use traits. For sharing a contract, use interfaces.

Chains of inheritance

A class can extend a class that extends another (Puppy extends Dog extends Animal). Keep such chains short. Deep hierarchies are hard to follow, because the code you need may be spread over many files.

Protected members

protected lets the child use the parent’s property, as $this->name above, while keeping it hidden from the outside.

lightbulb
Use inheritance sparingly
It ties the child tightly to the parent. If the parent changes, every child may break. Many modern PHP projects prefer small classes that are combined, rather than deep trees.