PHP Traits
A trait is a chunk of reusable code you can use inside multiple classes. PHP's answer to "I want this method in three unrelated classes without inheritance".
Defining one
PHP
trait Greets {
public function hello(): string {
return "Hi, {$this->name}";
}
}
Using it
PHP
class User {
use Greets;
public function __construct(public string $name) {}
}
class Robot {
use Greets;
public function __construct(public string $name) {}
}
echo (new User('Ada'))->hello(); // Hi, Ada
echo (new Robot('R2-D2'))->hello(); // Hi, R2-D2
Multiple traits
PHP
class Service {
use Greets, Loggable, Timestampable;
}
Conflict resolution
If two traits define a method with the same name, PHP makes you choose:
PHP
trait A { public function hi(): string { return 'A'; } }
trait B { public function hi(): string { return 'B'; } }
class C {
use A, B {
A::hi insteadof B; // resolve conflict
B::hi as hiFromB; // expose B's version under a new name
}
}
Abstract methods & properties in traits
PHP
trait Loggable {
abstract public function name(): string; // class must provide
public function log(string $msg): void {
echo '[', $this->name(), '] ', $msg, PHP_EOL;
}
}
Tip: Use traits sparingly. They're tempting but get hard to follow as a class accumulates them. Prefer composition (inject a collaborator) for new features.
Example
Example
<?php
trait Greet {
public function hello(): string { return "Hi, {$this->name}"; }
}
class User {
use Greet;
public function __construct(public string $name) {}
}
echo (new User('Ada'))->hello();
Try it Yourself »
Exercise
Pull a trait into a class with…
class User {
Greets; }
Three letters.
Discussion
Loading…