PHP Traits
In this page:
What are Traits?
A trait is a reusable block of methods that can be mixed into multiple, otherwise unrelated classes using the use keyword, solving the problem of sharing code between classes that don't share a common parent.
Example: What are Traits?
<?php
trait Greetable {
function greet() {
echo "Hello!";
}
}
class User {
use Greetable;
}
$user = new User();
$user->greet();
?>
Login to try C/C++/Java/PHP code in the editor
Defining and Using Traits
Unlike inheritance, a trait doesn't establish an is-a relationship — it's purely a mechanism to copy in a set of method implementations, so a Loggable trait could be used by both a User class and an Order class with no relation to each other.
Example: Defining and Using Traits
<?php
trait Loggable {
function log($msg) {
echo "[LOG] $msg\n";
}
}
class User {
use Loggable;
}
class Order {
use Loggable;
}
(new User())->log("User created");
(new Order())->log("Order placed");
?>
Login to try C/C++/Java/PHP code in the editor
Multiple Traits
A class can use multiple traits at once, and PHP has specific conflict-resolution rules (insteadof and as) for cases where two traits it uses happen to define a method with the same name.
Example: Multiple Traits
<?php
trait A {
function hello() { echo "A"; }
}
trait B {
function hello() { echo "B"; }
}
class MyClass {
use A, B {
A::hello insteadof B;
}
}
(new MyClass())->hello();
?>
Login to try C/C++/Java/PHP code in the editor
Conflict Resolution (insteadof)
Traits can define abstract methods too, requiring the class that uses them to supply an implementation, which lets a trait depend on behavior it expects the host class to provide.
Example: Conflict Resolution (insteadof)
<?php
trait Shape {
abstract function area();
function describe() {
echo "Area: " . $this->area();
}
}
class Square {
use Shape;
function area() {
return 16;
}
}
(new Square())->describe();
?>
Login to try C/C++/Java/PHP code in the editor
Trait Methods Visibility
Traits are a good fit for cross-cutting concerns like logging, timestamping, or serialization helpers that many otherwise-unrelated classes need, without forcing those classes into an artificial inheritance hierarchy.
Example: Trait Methods Visibility
<?php
trait Timestampable {
function timestamp() {
return date("Y-m-d");
}
}
class Post {
use Timestampable;
}
class Comment {
use Timestampable;
}
echo (new Post())->timestamp();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: