Multiple traits
Learn to combine capabilities by using multiple traits in a class.
Using more than one trait
A class can use more than one trait. In the use line you separate trait names with commas: use Logger, Notifier;. The class gains the methods of both traits.
Example:
class Order {
use Logger, Notifier;
}
$o = new Order();
$o->log("saved");
$o->notify("shipped");This lets you compose a class's capabilities from small, focused traits.
Trait composition
Using multiple traits strengthens composition in class design. Each trait carries one responsibility: Logger records, Notifier alerts, Cache stores. The class picks and combines the traits it needs.
This is more flexible than inheriting everything from one big parent class. Keeping each behavior in its own trait makes maintenance and testing easier.
Exercise Combine Logger and Notifier in the Order class
Define a Logger trait: its public function log(string $m): string method does return "[LOG] " . $m;. Define a Notifier trait: its public function notify(string $m): string method does return "[NOTIFY] " . $m;. Then an Order class uses both with use Logger, Notifier;. Create an instance with $o = new Order() and call echo $o->log("order received") . "\n" and echo $o->notify("shipped") . "\n".
Show example solution
First write trait Logger { ... } and trait Notifier { ... }. Then add class Order { use Logger, Notifier; }. With $o = new Order(); call both methods.
Example solution:
<?php
// Define Logger and Notifier traits, combine them in the Order class
trait Logger {
public function log(string $m): string {
return "[LOG] " . $m;
}
}
trait Notifier {
public function notify(string $m): string {
return "[NOTIFY] " . $m;
}
}
class Order {
use Logger, Notifier;
}
$o = new Order();
echo $o->log("order received") . "\n";
echo $o->notify("shipped") . "\n";
Test yourself
-
What is the correct way to add Logger and Notifier traits to a class?
- use Logger extends Notifier;
- use Logger, Notifier;
- class Order extends Logger, Notifier
- use Logger -> Notifier;
Show answer
use Logger, Notifier; — Correct. Trait names are separated by commas in the use line: use Logger, Notifier;
-
Complete the multiple trait usage
trait Logger { public function log() { return "log"; } } trait Notifier { public function notify() { return "notice"; } } class Order { use Logger, ____; } $o = new Order(); echo $o->notify() . "\n";Show answer
trait Logger { public function log() { return "log"; } } trait Notifier { public function notify() { return "notice"; } } class Order { use Logger, Notifier; } $o = new Order(); echo $o->notify() . "\n"; -
Match the trait to its capability
- Logger
- event recording
- Notifier
- sending alerts
- Serializer
- object to text
- Cache
- temporary storage