PHP Traits
A trait is a reusable bundle of methods that you can mix into any class, letting you share behavior without inheritance.
What problem do traits solve?
PHP allows a class to extend only one parent, which becomes a limitation when several unrelated classes all need the same helper methods. Traits solve this. A trait is a block of methods (and optionally properties) that you can insert into any class with the use keyword, as if the code had been written directly inside that class.
Defining and using a trait
<?php
trait Timestampable
{
public ?string $createdAt = null;
public function touch(): void
{
$this->createdAt = date("Y-m-d");
}
}
class Article
{
use Timestampable;
public function __construct(public string $title)
{
}
}
class Comment
{
use Timestampable;
}
$a = new Article("Learning PHP");
$a->touch();
echo $a->createdAt; // today's date, e.g. 2026-07-15
?>Both Article and Comment gain the touch method and the createdAt property from the trait, even though the two classes are otherwise unrelated and neither extends the other. The trait code is effectively copied into each class at compile time.
Using several traits together
A class can pull in more than one trait, either by listing them on separate use lines or by separating their names with commas. This lets you compose a class from several small, single-purpose behaviors.
Combining multiple traits
<?php
trait Loggable
{
public function log(string $message): string
{
return "[LOG] " . $message;
}
}
trait Serializable
{
public function toJson(): string
{
return json_encode(get_object_vars($this));
}
}
class Report
{
use Loggable, Serializable;
public string $title = "Monthly";
}
$r = new Report();
echo $r->log("created"); // [LOG] created
echo "\n";
echo $r->toJson(); // {"title":"Monthly"}
?>Handling method name conflicts
If two traits define a method with the same name, PHP reports a conflict that you must resolve. The insteadof operator chooses which trait's method to keep, and the as operator can give the other one an alias so both remain available under different names.
- Declare a trait with the trait keyword, then include it in a class with use.
- A class can use multiple traits at once.
- Traits can define both methods and properties.
- Use insteadof and as to resolve method name clashes between traits.
- Traits are for sharing behavior; they cannot be instantiated on their own.