📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners OOP — Inheritance

OOP — Inheritance

6 min read Quiz at the end
Inheritance lets one class extend another and reuse its code. The child gets all methods and properties of the parent. Use extends and call parent::__construct() to initialize the parent properly in the child class.

Inheritance

class Animal {
    public function __construct(
        protected string $name,
        protected string $sound
    ) {}

    public function speak(): string {
        return "{$this->name} says {$this->sound}";
    }

    public function getName(): string {
        return $this->name;
    }
}

class Dog extends Animal {
    public function __construct(string $name) {
        parent::__construct($name, "Woof");
    }

    public function fetch(): string {
        return "{$this->name} fetches the ball!";
    }

    // Override parent method
    public function speak(): string {
        return parent::speak() . "!";
    }
}

$dog = new Dog("Rex");
echo $dog->speak();   // Rex says Woof!
echo $dog->fetch();   // Rex fetches the ball!
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which keyword extends a class?
💡 class Child extends Parent {} is the PHP inheritance syntax.
2. How do you call the parent constructor?
💡 parent::__construct() calls the parent class constructor.
3. Can PHP extend multiple classes?
💡 PHP supports only single inheritance. Use interfaces/traits for multiple behaviour.
4. What does method overriding mean?
💡 Overriding means redeclaring a parent method in a child class with new behaviour.
5. Which keyword prevents a class from being extended?
💡 final class MyClass {} prevents the class from being extended.