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
trait FormatDollars { ... }declares the trait. It holds ordinary methods.use FormatDollars;inside the class body (the part between the class's{and}) adds the trait to the class. From then ondollars()works as if it were written in that class.$thisinside a trait method is the object of the class using it. The traitFormatDollarshas no properties of its own. A trait method can read the class's properties through$this: if the trait writes$this->name, the class must have a$nameproperty.- String functions from the String lesson work as usual inside a trait. In the exercise, you use
strtoupper($this->name)for upper case andstrtolower($this->name)for lower case. number_format($amount, 2)writes the number with two decimals and a comma between thousands: 1250 becomes1,250.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
insteadofpicks: thedollars()ofFormatDollarsis used, not the one ofFormatShort.asgives a second name: theFormatShortversion stays available asdollarsShort().
💡 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;
}
}
- A class that adds
Discountablemust writeprice(): int. Say the classDrinkforgets it. PHP refuses:Class Drink contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Drink::price). - When
price()returns 20,discountedPrice(10)(a 10 percent discount) returns18. - A
staticproperty in a trait is copied into each class that uses it, so each class has its own count. IfMenuandOrderboth useCounter, callingMenu::increment()twice and thenOrder::increment()once gives 1, 2, then 1.
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
usein the wrong place.useat the top of a file, outside a class, makes a short name for a class from another namespace (the Namespaces & Autoloading lesson). A trait is added withuseinside the class body.- Property names that don't match. Say a trait reads
$this->name, but the property of the classCityis called$title. The result isWarning: Undefined property: City::$name, and the text it gives is empty. In the exercise, the property ofCityis$name. - Two traits, one method name, no
insteadof. The file doesn't run at all. Pick withinsteadof, keep the other withas. - A trait for everything. If a method is only used by one class, just write it in that class.
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().