PHP 8 Advanced OOP · 10 min read

PHP Inheritance, Interfaces, and Contracts

Lesson 13 of 43 in the PHP 8 learning path.

When should I use an interface instead of extending a base class?

An interface names a contract without storing a parent implementation. Notifier says that some object can send a student name and a message. EmailNotifier fulfills that contract and keeps its own from address. EnrollmentDesk does not extend EmailNotifier. It receives a Notifier in the constructor and calls send(). That is composition: the desk has a notifier. A subclass would claim the desk is a kind of email sender, which becomes false the moment the school adds a second channel.

Extend a class when the child truly is the parent and should reuse protected behavior. Reach for an interface when several types share only the calls the rest of the program makes. PHP 8.3 adds the Override attribute, and EmailNotifier marks send() with #[\Override] so a renamed interface method fails at compile time instead of leaving a new unused method behind. The desk stays small because the mail transport can change without a new EnrollmentDesk subclass for every channel.

Syntax & Parameters

Syntax
interface Notifier { public function send(string $studentName, string $message): void; }
final class EnrollmentDesk { public function __construct(private readonly Notifier $notifier) {} }

Example

src/Notifier.php
<?php

declare(strict_types=1);

interface Notifier
{
    public function send(string $studentName, string $message): void;
}

final class EmailNotifier implements Notifier
{
    private string $lastMessage = '';

    public function __construct(private readonly string $fromAddress)
    {
        if (filter_var($fromAddress, FILTER_VALIDATE_EMAIL) === false) {
            throw new InvalidArgumentException('From address must be an email.');
        }
    }

    #[\Override]
    public function send(string $studentName, string $message): void
    {
        $name = trim($studentName);
        $body = trim($message);
        if ($name === '' || $body === '') {
            throw new InvalidArgumentException('Name and message are required.');
        }
        $this->lastMessage = $body;
    }

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

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

final class EnrollmentDesk
{
    public function __construct(private readonly Notifier $notifier)
    {
    }

    public function confirm(string $studentName): string
    {
        $name = trim($studentName);
        if ($name === '') {
            throw new InvalidArgumentException('Student name is required.');
        }
        $message = 'You are enrolled, ' . $name . '.';
        $this->notifier->send($name, $message);

        return $message;
    }
}

$notifier = new EmailNotifier('desk@example.com');
$desk = new EnrollmentDesk($notifier);
$sent = $desk->confirm('Amina Cruz');

echo 'message=' . $sent . "\n";
echo 'from=' . $notifier->fromAddress() . "\n";
echo 'stored=' . $notifier->lastMessage() . "\n";
echo "channel=email\n";

Expected Output

message=You are enrolled, Amina Cruz.
from=desk@example.com
stored=You are enrolled, Amina Cruz.
channel=email

Line-by-Line Walkthrough

  1. declare(strict_types=1) checks the new EmailNotifier() and EnrollmentDesk calls written in this file.
  2. Notifier is an interface with one method, send(), and no properties or parent body.
  3. EmailNotifier implements Notifier and stores a readonly from address plus the last message it accepted.
  4. The constructor rejects a from address that filter_var() does not accept as an email.
  5. #[\Override] on send() tells PHP 8.3 that this method must match the interface. A renamed contract method becomes a fatal error.
  6. send() trims the name and the body and stores the body. A real mailer would hand that body to a transport here.
  7. EnrollmentDesk takes a Notifier in its constructor. The type is the interface, so the desk is not a subclass of EmailNotifier.
  8. confirm() builds "You are enrolled, Amina Cruz." and passes it to the notifier. That is composition: the desk has a notifier.
  9. The runner constructs an EmailNotifier with desk@example.com and passes it into the desk.
  10. The echoes print the returned message, the from address, the stored body, and the channel label email.

Common Pitfalls & Security

Inheritance feels shorter until a second channel arrives. A BaseNotifier with a protected mailer property forces every channel to look like email. An interface plus a constructor argument keeps the desk stable. The message text is still untrusted if a name came from a form: this sample stores it, and the HTML page that prints it still has to escape it.

  • Extending EmailNotifier to make a desk "reuse send()" couples enrollment policy to SMTP details. Pass a Notifier instead.
  • Forgetting implements Notifier means the class is not accepted by EnrollmentDesk, even if it has a send() method. The contract is the implements clause and the signature.
  • #[\Override] on a method that matches nothing is a fatal error. That is the point: the attribute catches a drift between the interface and the class.
  • Unsafe anti-pattern (do not ship): echo $message; into an HTML mail body with a raw student name. Encode HTML in the template. The interface does not do it for you.
  • A deep tree of abstract classes that only forward calls is harder to test than one interface and two final classes.
  • Putting the from address in a global function hides the dependency. The constructor makes desk@example.com visible at the call site.

Best Practices & Modern Standards

On PHP 8.3, mark interface implementations with #[\Override], keep the implementing classes final unless you are designing for extension, and type the constructor parameter as the interface. Composition is the usual way to add a notifier, a clock, or a repository to a desk object. Inheritance remains appropriate when a subtype truly shares and specializes a parent implementation.

Depend on Notifier in the grade-book workflow and construct EmailNotifier at the edge, where configuration such as the from address is known. Tests can pass a second implementation that records messages in an array. The desk code stays the same because it only calls send().

Real-World Use

When a student finishes the enrollment form, EnrollmentDesk::confirm() tells the notifier to record "You are enrolled, Amina Cruz." The production edge wires EmailNotifier with the school from address. A later SMS notifier implements the same send() method and is passed into the same desk. The desk does not grow a subclass for each channel, and the from address stays on the email implementation.

Frequently Asked Questions

When is a subclass the better tool?

When the new type is the parent type and should reuse real behavior, such as a specialized report that shares a rendering helper. A desk that only needs to call send() is a collaborator, so it takes a Notifier.

What does #[Override] check?

PHP 8.3 checks that the method actually overrides an interface or parent method. If send() is removed from Notifier and the attribute remains, the file fatals instead of keeping a method nobody calls.

Can EnrollmentDesk construct EmailNotifier itself?

It can, and then every test and every new channel has to edit the desk. Receiving a Notifier in the constructor keeps the choice of email at the composition root.

Does an interface replace validation?

No. The interface fixes the method names and types. EmailNotifier still rejects a bad from address, and the HTML layer still escapes the message before a browser sees it.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…