Traits in PHP
Sharing behavior across classes without inheritance.
<?php
// a trait holds methods; use mixes them into any class
trait Greets {
public function greet(): string {
return "hi, I am " . $this->name();
}
}
class Robot {
use Greets;
public function __construct(private int $id) {}
public function name(): string {
return "unit-" . $this->id;
}
}
echo (new Robot(7))->greet(), "\n";
How it works
- A
traitdefines methods with no class of their own. use Greets;copies them intoRobotas instance methods.- The trait calls
$this->name(), which the host class provides.
Keywords and builtins used here
Robotclassechofunctiongreetnamenewprivatepublicreturntraituse
The run, in numbers
- Lines
- 19
- Characters to type
- 329
- Tokens
- 70
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 52 seconds.
Step 3 of 3 in Classes, step 18 of 27 in Language basics.