Inheritance

A class can inherit properties and methods from a parent class.

Syntaxclass Child extends Parent { ... }

Inheritance lets a class reuse the code of another class. Use the extends keyword. The new class (child) gets all the public and protected members of the parent.

A child class can override a parent method by redefining it, and reach the parent version with parent::.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Create a SavingsAccount class that extends BankAccount and adds an interest-rate calculation method.
  • Build a hierarchy of Shape subclasses (Circle, Rectangle) that each override an area() method.
  • Inherit shared HTTP client setup in an ApiClient base class and extend it for each third-party service.

More examples

Basic class extension

extends inherits all public and protected members; speak() is overridden to give Dog its own behaviour.

Example · php
<?php
class Animal {
    public function __construct(public string $name) {}
    public function speak(): string {
        return '...';
    }
}

class Dog extends Animal {
    public function speak(): string {
        return "{$this->name} says Woof!";
    }
}

$d = new Dog('Rex');
echo $d->speak(); // Rex says Woof!

Calling parent methods

parent:: calls the overridden version from the parent class, letting the child augment rather than replace behaviour.

Example · php
<?php
class Vehicle {
    public function describe(): string {
        return 'I am a vehicle';
    }
}

class Car extends Vehicle {
    public function describe(): string {
        return parent::describe() . ' — specifically a car';
    }
}

echo (new Car())->describe();
// I am a vehicle — specifically a car

Abstract shape hierarchy

An abstract base class provides shared describe() logic while forcing each concrete subclass to implement area().

Example · php
<?php
abstract class Shape {
    abstract public function area(): float;
    public function describe(): string {
        return get_class($this) . ' area: ' . $this->area();
    }
}
class Circle extends Shape {
    public function __construct(private float $r) {}
    public function area(): float { return M_PI * $this->r ** 2; }
}
class Square extends Shape {
    public function __construct(private float $s) {}
    public function area(): float { return $this->s ** 2; }
}

foreach ([new Circle(5), new Square(4)] as $shape) {
    echo $shape->describe() . "\n";
}

Discussion

  • Be the first to comment on this lesson.