PHP Traits
PHP classes can only inherit from one parent. So what do you do when two unrelated classes — say Invoice and UserProfile — both need the same handful of helper methods? Copy-pasting is error-prone, and forcing them into a common parent class makes no sense.
The answer is a trait: a reusable bundle of methods (and properties) that you "paste" into a class with the use keyword. The code is copied in at compile time, so the class behaves as if you had written those methods yourself.
Declaring and using a trait
<?php
trait Greets
{
public function hello(): string
{
return "Hello from " . static::class;
}
}
class Robot
{
use Greets;
}
class Teacher
{
use Greets;
}
echo (new Robot())->hello(), "\n";
echo (new Teacher())->hello(), "\n";Hello from Robot
Hello from Teacher
static::class resolves to the class that is actually using the trait, so the same method prints different names.
Traits with properties
A trait can carry state too. Each class that uses it gets its own copy of the properties.
<?php
trait Timestamps
{
private ?string $createdAt = null;
private ?string $updatedAt = null;
public function touch(string $when): void
{
$this->createdAt ??= $when;
$this->updatedAt = $when;
}
public function history(): string
{
return "created {$this->createdAt}, updated {$this->updatedAt}";
}
}
class Article
{
use Timestamps;
public function __construct(public string $title) {}
}
$a = new Article("Traits in PHP");
$a->touch("2025-01-10");
$a->touch("2025-02-03");
echo $a->title, ": ", $a->history(), "\n";Traits in PHP: created 2025-01-10, updated 2025-02-03
Using several traits
List several traits with commas. A class can also combine traits with inheritance and interfaces freely.
<?php
trait Loggable
{
private array $log = [];
public function log(string $msg): void
{
$this->log[] = $msg;
}
public function dumpLog(): void
{
foreach ($this->log as $i => $line) {
echo $i + 1, ". ", $line, "\n";
}
}
}
trait Discountable
{
public function discounted(float $price, int $percent): float
{
return round($price * (100 - $percent) / 100, 2);
}
}
class Shop
{
use Loggable, Discountable;
public function sell(string $item, float $price): void
{
$final = $this->discounted($price, 15);
$this->log("$item sold for $final");
}
}
$shop = new Shop();
$shop->sell("Lamp", 40);
$shop->sell("Chair", 79.9);
$shop->dumpLog();1. Lamp sold for 34
2. Chair sold for 67.92
Resolving name conflicts
If two traits define a method with the same name, PHP stops with a fatal error unless you decide which one wins. Use insteadof to choose, and as to keep the other under an alias:
<?php
trait English
{
public function greet(): string { return "Hello"; }
}
trait Spanish
{
public function greet(): string { return "Hola"; }
}
class Guide
{
use English, Spanish {
English::greet insteadof Spanish;
Spanish::greet as greetSpanish;
}
}
$g = new Guide();
echo $g->greet(), " / ", $g->greetSpanish(), "\n";Hello / Hola
as can also change visibility, for example helper as protected;.
Precedence order
When the same method exists in several places, PHP picks in this order:
| Priority | Source |
|---|---|
| 1 (highest) | A method written directly in the class |
| 2 | A method from a trait the class uses |
| 3 (lowest) | A method inherited from the parent class |
So a class can always override a trait method, and a trait method overrides the parent's.
Abstract and static members in traits
A trait may declare abstract methods to demand that the using class supplies them, and it can contain static methods and properties as well.
<?php
trait Describes
{
abstract public function label(): string;
public function describe(): string
{
return "[" . strtoupper($this->label()) . "]";
}
public static function make(): static
{
return new static();
}
}
class Coffee
{
use Describes;
public function label(): string { return "espresso"; }
}
echo Coffee::make()->describe(), "\n";[ESPRESSO]
Tip: Traits are great for small, focused behaviours (logging, timestamps, comparisons). If a trait grows large or needs lots of shared state, a separate class that you inject is usually the cleaner design.
Note: A trait cannot be instantiated on its own and does not count as a type: you cannot type-hint a parameter as a trait. Pair a trait with an interface when you need both shared code and a type to check against.
Test yourself
Which keyword adds a trait's methods to a class?
extendsimplementsuseinclude
Two traits both define greet(). How do you pick trait A's version?
A::greet as B;A::greet insteadof B;B::greet override A;- PHP picks the first trait automatically
A class, its trait and its parent all define run(). Which one is called?
- The parent's
- The trait's
- The class's own
- PHP throws an error