Advanced OOP — PHP

extends makes a child class inherit the contents (properties and methods) of its parent class, and a class may have only one parent. A method written again in…

Mrs. Tini's Stall now sells food and drinks. The classes Food and Drink both need a name, a price and info(). If you write both from scratch, the constructor and info() have to be copied twice. Every change has to be made twice too.

In the OOP Basics lesson you made one class and a few objects from it. In this lesson, classes start to relate to each other. One class can inherit the contents of another (inheritance): it gets the other class's properties and methods without writing them again. The class that inherits is called the child class, and the class it inherits from is called the parent class. A parent class can also be left unfinished on purpose, so its child classes finish it (abstract class). And a class can promise to have certain methods (interface).

Picture the menu book at Mrs. Tini's Stall. Every page is printed from the same template, so the spots for name and price are already there. The "category" field is left blank on the template, and every page must fill it in. The blank template itself is never put in the menu book. Some pages get a "Can Be Delivered" sticker, a sign that the page has a delivery fee. In code, the template is the parent class, each page is a child class, the blank field is an abstract method, and the sticker is an interface.

Inheritance: extends inherits the parent's contents

In this code, Drink inherits the contents of Menu:

<?php
class Menu {
    public function __construct(public string $name, public int $price) {}

    public function info(): string {
        return "$this->name - \$$this->price";
    }
}

class Drink extends Menu {
    public function info(): string {
        return parent::info() . " (with ice)";
    }
}

$tea = new Drink("Iced Tea", 5);
echo $tea->info(); // Iced Tea - $5 (with ice)

A class may extends only one parent. Who may use a property or method is set by its visibility (the access rule), the keyword in front of it:

Keyword Usable from When broken from outside the class
public anywhere
protected the class itself and its children Cannot access protected property Menu::$price
private the class itself only, not even its children Cannot access private property Menu::$stock

Abstract class: a parent left unfinished on purpose

In this code, Menu is made abstract, and Food completes it:

<?php
abstract class Menu {
    public function __construct(public string $name, public int $price) {}

    abstract public function category(): string;

    public function info(): string {
        return $this->category() . ": $this->name - \$$this->price";
    }
}

class Food extends Menu {
    public function category(): string {
        return "Food";
    }
}

$rice = new Food("Fried Rice", 15);
echo $rice->info() . "\n";

$menu = new Menu("Fried Rice", 15);
echo "this line never runs";

The result in the terminal:

$ php menu.php
Food: Fried Rice - $15

Fatal error: Uncaught Error: Cannot instantiate abstract class Menu in /var/www/stall/menu.php:21
Stack trace:
#0 {main}
  thrown in /var/www/stall/menu.php on line 21

In this lesson's exercise, the pattern is the same: abstract class Shape with the abstract method area(), then the classes Circle and Triangle, each filling in its own area formula.

Interface: a promise to have certain methods

In this code, Food and Drink promise that they can be delivered:

interface Deliverable {
    public function deliveryFee(int $distanceKm): int;
}

class Food extends Menu implements Deliverable {
    public function category(): string { return "Food"; }
    public function deliveryFee(int $distanceKm): int { return 2 * $distanceKm; }
}

class Drink extends Menu implements Deliverable {
    public function category(): string { return "Drink"; }
}

The result in the terminal:

$ php menu.php

Fatal error: Class Drink contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Deliverable::deliveryFee) in /var/www/stall/menu.php on line 21

How an abstract class and an interface differ:

Abstract class Interface
Holds properties, a constructor, full methods, abstract methods methods with no body
Used with extends, one parent implements, many allowed
Fits children that share data and code unrelated classes that need the same ability

💡 final, then self:: versus static::

final locks a method or a class so a child class can't change it. In this code, info() is locked, so Promo may not write info() again:

abstract class Menu {
    // ...
    final public function info(): string {
        return "$this->name - \$$this->price";
    }
}

class Promo extends Menu {
    public function info(): string { return "FREE"; }
}
// Fatal error: Cannot override final method Menu::info()

final class Till {} locks the whole class, so no class may inherit from it. class CheatingTill extends Till {} is refused with Class CheatingTill cannot extend final class Till.

A static method is called through the class name and ::, with no object. Inside that method, self and static both point at a class, but they can point at different classes. In this code, create() is written in Menu but called through Food:

abstract class Menu {
    // ...
    public static function create(string $name, int $price): static {
        return new static($name, $price);
    }
}

$rice = Food::create("Fried Rice", 15);
echo get_class($rice); // Food

💡 Enums with methods

An enum is a type with a closed list of values: its value can only be one from that list. An Iced Tea glass size is only S or L, nothing else:

enum Size: string {
    case Small = "S";
    case Large = "L";

    public function extra(): int {
        return match ($this) {
            Size::Small => 0,
            Size::Large => 3,
        };
    }
}

$u = Size::from("L");
echo $u->name;              // Large
echo $u->value;             // L
echo 5 + $u->extra(); // 8
var_dump(Size::tryFrom("XL")); // NULL
Size::from("XL"); // ValueError: "XL" is not a valid backing value for enum Size

⚠️ Rejected classes and an area that's slightly off

TL;DR: extends makes a child class inherit the contents (properties and methods) of its parent class, and a class may have only one parent. A method written again in the child overrides the parent's version, and parent:: calls the parent's version. public works from anywhere, protected from the class and its children, and private from the class itself only. An abstract class (a class left unfinished on purpose) can't be new-ed (Cannot instantiate abstract class), and its abstract methods must be filled in by the children. An interface is a promise to have a certain list of methods. It is attached with implements (many allowed), and PHP checks it when the class is read. final locks a method or class, so it can't be overridden or inherited. new static makes an object of the class used to call the method, while new self makes one of the class the code is written in. An enum is a closed list of values that may have methods. In the exercise, use M_PI (PHP's value of pi) for a circle's area.

⚡ extends inherits the parent's contents

Write:

class Drink extends Menu {
    public function info(): string {
        return parent::info() . " (with ice)";
    }
}

$tea = new Drink("Iced Tea", 5);
echo $tea->info(); // Iced Tea - $5 (with ice)

Meaning: extends makes Drink (the child class) inherit Menu's properties, constructor and info() (Menu is the parent class). Writing info() again in Drink is called an override: the child's version is used. parent::info() runs the parent's version first. A class may have only one parent.

⚡ An abstract class can't be new-ed

Guess first: the word abstract marks a class left unfinished on purpose. Menu is written abstract class Menu. What happens at new Menu("Fried Rice", 15)?

PHP stops with Cannot instantiate abstract class Menu (instantiate means to make an object). The object is never made.

Meaning: An abstract class can only be used as a parent class. Its abstract methods, like abstract public function category(): string;, have no body yet, and every child class must write them. Objects are made from those child classes.

⚡ An interface is a promise

Write:

interface Deliverable {
    public function deliveryFee(int $distanceKm): int;
}

Meaning: An interface is a list of methods with no body, like a promise. A class that writes implements Deliverable must have the method deliveryFee(). PHP checks this when it reads the class, before any object exists. A class may implements many interfaces, but still only one extends (one parent).

What you will learn