PHP Tutorial · Object-Oriented PHP · Lesson 31 of 38

PHP Inheritance

Extend classes, override methods and call parent methods.

extends

A child class inherits the public and protected members of its parent and can override methods. parent::method() calls the parent's version:

Example 1Try it yourself
<?php
class Notification
{
    public function __construct(protected string $message) {}

    public function send(): string
    {
        return "Sending: {$this->message}";
    }
}

class EmailNotification extends Notification
{
    public function __construct(string $message, private string $to)
    {
        parent::__construct($message);
    }

    public function send(): string
    {
        return parent::send() . " (email to {$this->to})";
    }
}

$notes = [new Notification("Hello"), new EmailNotification("Welcome!", "[email protected]")];
foreach ($notes as $n) {
    echo $n->send(), "\n";
}
var_dump($notes[1] instanceof Notification);

Output

Sending: Hello
Sending: Welcome! (email to [email protected])
bool(true)

final

A final class can't be extended; a final method can't be overridden. Many teams make classes final by default and prefer composition (objects holding other objects) over deep inheritance trees.

Test yourself

How do you call the parent class's version of a method?

  1. super.method()
  2. parent::method()
  3. $this->parent()
  4. base.method()
Show answer

Answer: parent::method()