Traits & Interfaces — PHP

A trait is a set of methods that several classes share. trait Name { ... } declares it, and use Name; inside a class body adds it, as if the methods were…

The method dollars() writes 15 as "$15.00". It is needed in the class Menu, and in the class Order too. Copy it into both classes? Once the format changes, you have to remember to change both. Inherit it with extends? Order is not a kind of Menu, and a class can only have one parent.

A trait solves this without extends. A trait is a set of methods you can add to many classes at once, without a parent and child relationship. Picture the price stamp at Mrs. Tini's Stall that prints "$15.00". The menu board uses that stamp, and the receipt does too, yet the menu board is not a receipt. A trait works like that price stamp: one piece of code, used in several classes that have no parent and child relationship. In the example below, the stamp is the trait FormatDollars, the menu board is the class Menu, and the receipt is the class Order. When the file is read, PHP copies the trait's methods into every class that uses it.

Trait: methods used together

In this code, both classes use the same trait:

<?php
trait FormatDollars {
    public function dollars(int $amount): string {
        return '$' . number_format($amount, 2);
    }
}

class Menu {
    use FormatDollars;

    public function __construct(public string $name, public int $price) {}

    public function label(): string {
        return $this->name . " " . $this->dollars($this->price);
    }
}

class Order {
    use FormatDollars;

    public function __construct(public int $total) {}

    public function receipt(): string {
        return "Total " . $this->dollars($this->total);
    }
}

echo (new Menu("Fried Rice", 15))->label() . "\n";
echo (new Order(20))->receipt() . "\n";
Fried Rice $15.00
Total $20.00

Why not use extends?

In the Advanced OOP lesson, you wrote Food extends Menu. But a PHP class may have only one parent. extends also means "is a kind of". Order is not a kind of Menu, so extending Menu just to get dollars() would say the wrong thing. A trait has no one-parent rule. One trait may be added to any number of classes, and one class may add several traits at once, for example use FormatDollars, HasDiscount;. That is a trait's main advantage: it can be used in many classes, without the one-parent limit.

Two traits, the same method name

Say there is a second trait, FormatShort, that also has a method dollars(). The class Menu adds both:

trait FormatShort {
    public function dollars(int $amount): string {
        return '$' . $amount;
    }
}

class Menu {
    use FormatDollars, FormatShort;
    // ...
}

PHP refuses the file before a single line runs:

PHP Fatal error:  Trait method FormatShort::dollars has not been applied as Menu::dollars, because of collision with FormatDollars::dollars in /app/menu.php on line 14

The word collision in that message means two names hit each other: two traits copy dollars() into the same class, and PHP doesn't guess which one you want. You decide, in a { } block after use:

class Menu {
    use FormatDollars, FormatShort {
        FormatDollars::dollars insteadof FormatShort;
        FormatShort::dollars as dollarsShort;
    }
    // ...
}

$menu = new Menu("Fried Rice", 15);
echo $menu->label() . "\n";
echo $menu->dollarsShort(15) . "\n";
Fried Rice $15.00
$15

💡 Abstract and static in a trait

A trait may ask the class using it for a method with abstract. A trait may also have static members (properties and methods that belong to the class, from the OOP Basics lesson):

trait Discountable {
    abstract public function price(): int;

    public function discountedPrice(int $percent): int {
        return $this->price() - intdiv($this->price() * $percent, 100);
    }
}

trait Counter {
    private static int $count = 0;

    public static function increment(): int {
        return ++self::$count;
    }
}

Trait, interface, or extends?

Tool Answers Example
interface what it must be able to do, no body PaymentMethod with pay()
trait how to do it, a body that is copied FormatDollars with dollars()
extends this class is a kind of another class, one parent only Food extends Menu

A trait is not a type: you can't use a trait's name the way you use a class name. new FormatDollars() is refused with Error: Cannot instantiate trait FormatDollars, and a parameter FormatDollars $x never matches any object. When you need a type, pair the trait with an interface: class Menu implements Formattable { use FormatDollars; }. The interface promises which methods exist, and the trait fills in their code.

⚠️ Plugged in the wrong place, or clashing names

TL;DR: A trait is a set of methods that several classes share. trait Name { ... } declares it, and use Name; inside a class body adds it, as if the methods were written in that class. $this in a trait is the object of the class using it, so the trait can read that class's properties. Its advantage: one trait can be used in many classes without the one-parent limit of extends, and one class may use A, B;. Two traits in one class with a method of the same name cause a collision Fatal error (two names that hit each other), solved with insteadof (pick one) and as (give a second name). A trait may have abstract methods (the class must write them) and static members (each class gets its own copy). A trait is not a type (its name can't be a parameter type) and cannot be newed. An interface promises which methods exist, a trait fills in their code, and extends says this class "is a" kind of another class.

⚡ Trait: methods used together

Write:

trait FormatDollars {
    public function dollars(int $amount): string {
        return '$' . number_format($amount, 2);
    }
}

class Order {
    use FormatDollars;
}

Meaning: A trait is a set of methods you can add to many classes, here FormatDollars with the method dollars(). use FormatDollars; inside the class body adds the trait, as if dollars() were written in the class Order itself. $this inside a trait is the object of the class using it, so the trait can read that class's properties.

⚡ Why not extends

Guess first: extends passes the contents of one parent class down to its child class. Compared with ordinary extends, where does a trait win?

It can be used in many classes. A class may have only one parent, but one class may use FormatDollars, HasDiscount; (adding two traits), and one trait may be used by any class.

Meaning: A trait is not a type (its name can't be a parameter type) and can't be newed, so no object is ever created from a trait. An interface promises which methods exist, a trait fills in their code, and extends says this class "is a" kind of another class.

⚡ Two traits, the same method name

Write:

class Menu {
    use FormatDollars, FormatShort {
        FormatDollars::dollars insteadof FormatShort;
        FormatShort::dollars as dollarsShort;
    }
}

Meaning: The traits FormatDollars and FormatShort both have a method dollars(). Without this { } block, PHP refuses the file with a collision Fatal error (two names that hit each other). insteadof picks the version that's used, here the one from FormatDollars. as gives the other version a second name: dollarsShort().

What you will learn