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)
class Drink extends Menumeans Drink inherits everything in Menu:$name,$price, the constructor andinfo(). Menu is the parent class, and Drink is the child class.new Drink("Iced Tea", 5)uses Menu's constructor, because Drink doesn't write one of its own.- Drink writes
info()again with the same name. This is called an override: for a Drink object, the child's version ofinfo()is used. parent::info()runs the parent's version ofinfo()first, then the child's version adds some text. So the parent's method doesn't have to be copied.
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
abstract class Menumeans Menu can only be used as a parent class. The error message uses the word instantiate, which means to make an object withnew. PHP refuses to do that for an abstract class, so the object is never made and the script stops at line 21.abstract public function category(): string;is an abstract method: a method with no body (no{ }), ending in a semicolon. It means "every child class must write this method".info()in the parent already calls$this->category(), even thoughcategory()has no body in the parent. That's safe, because a Menu object can't be made. Any object that exists comes from a child class, and that child class has writtencategory().- A child class that forgets to write
category()is refused when its class is read:Class Food contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Menu::category).
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
- An
interfaceholds only a list of methods: the name, parameters and return type of each method, with no body. An interface can't benew-ed (you can't make an object from it). implements Deliverableis a promise: this class will have every method in that interface. PHP checks the promise when it reads the class, before any object is made. Drink has nodeliveryFee()yet, so PHP stops at theclass Drinkline. That is line 21 of the full file, which also holds theMenuclass from the previous section.- If you add
deliveryFee()to Drink, for example withreturn 1 * $distanceKm;, the error goes away. The delivery fee for Iced Tea over 3 km becomes $3, and for Fried Rice over 3 km $6. - A class may
implementsmany interfaces at once (implements Deliverable, Countable), but still only oneextends.Countableis an interface built into PHP. $menu instanceof Deliverableanswerstruewhen the object's class hasimplements Deliverable, directly or through its parent class. This check is useful before callingdeliveryFee().
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
new staticmakes an object of the class that was called, here Food. That is whyget_class($rice)(the class name of an object) answersFood. This is called late static binding: the class is only decided when the method is called.- If
create()usednew self, the object would be made from the class the code is written in, which is Menu. Since Menu is abstract,Food::create(...)would end inCannot instantiate abstract class Menu. - The same goes for class names. In a method written in Menu and called through
Food::...,static::classholdsFood, whileself::classholdsMenu.
💡 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
case Small = "S";is one enum value.: stringmakes it a backed enum: every case carries a string value.->nameholds the case's name,->valueholds its string value, andSize::cases()gives a list of every case (2 here).from()turns text into a case. When no case matches,from()throws (raises) aValueError.tryFrom()only returnsnull, with no error.- An enum may have methods like a class.
match ($this)picks a result by case:Largeadds 3.
⚠️ Rejected classes and an area that's slightly off
newon an abstract class.new Menu(...)ornew Shape()is always refused withCannot instantiate abstract class. Make your objects from the child classes.- Forgetting a required method. An abstract method in the parent must be written in the child class, and a method in an interface must be written in the class that has
implements, with the same name and return type. If not, PHP stops withcontains 1 abstract method. - Expecting
privateto work in a child. A child class can't read its parent'sprivateproperty. Useprotectedwhen the child needs it. - Typing pi yourself. In the exercise, the area of a circle with radius 7, calculated as
3.14 * 7 * 7, gives 153.86, not 153.94. Use the built-in constantM_PI(the value of pi that PHP already provides), thenround($x, 2)rounds it to153.94.
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).