Traits
A trait is a small bundle of methods that many classes can share. A class uses a trait to take its methods as its own.
One trait used by one class
The Logger trait holds one log method. Page takes the trait with the word use, and the page object can then run log.
<?php
trait Logger {
public function log($message) {
echo "Log: " . $message . "\n";
}
}
class Page {
use Logger;
}
$page = new Page();
$page->log("Page opened");Two traits in one class
Host uses Greeter and Farewell in one use line. The host object answers both calls, one from each trait.
<?php
trait Greeter {
public function hello() {
echo "Hello\n";
}
}
trait Farewell {
public function bye() {
echo "Goodbye\n";
}
}
class Host {
use Greeter, Farewell;
}
$host = new Host();
$host->hello();
$host->bye();A name clash settled with insteadof and as
Greeter and Welcomer both define a method named hello. The use block keeps the Greeter version under hello and gives the Welcomer version the new name welcomeHello.
<?php
trait Greeter {
public function hello() {
echo "Hello from Greeter\n";
}
}
trait Welcomer {
public function hello() {
echo "Hello from Welcomer\n";
}
}
class Host {
use Greeter, Welcomer {
Greeter::hello insteadof Welcomer;
Welcomer::hello as welcomeHello;
}
}
$host = new Host();
$host->hello();
$host->welcomeHello();Example
<?php
trait Logger {
public function log($message) {
echo "Log: " . $message . "\n";
}
}
trait Stamp {
public function stamp() {
echo "Stamped\n";
}
}
class Report {
use Logger, Stamp;
public function title() {
echo "Weekly report\n";
}
}
$report = new Report();
$report->title();
$report->stamp();
$report->log("Report saved");Key points
- A trait holds methods that classes can share.
- The word use inside a class takes a trait for that class.
- Methods from a trait act as methods of the class that uses it.
- A class can use more than one trait.
- A name clash between two traits must be settled by the class that uses them.
- The word insteadof picks which trait method keeps a shared name.
- The word as gives the other method a second name in the class.
In this example, the Report class writes its own title method. It takes the stamp method from the Stamp trait and the log method from the Logger trait. The three calls print the title, the stamp and the log line in order.
Note
One trait can serve many unrelated classes, since a trait needs no parent class.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Two traits in one class both define a method named hello. Which word picks the trait that keeps the name hello?