A PHP trait is a reusable bundle of methods (and optionally properties) that you drop into multiple classes using the use keyword inside the class body. Because PHP only lets a class extend one parent class, traits let unrelated classes like Article, Tutorial, and User share capabilities such as slug generation or audit timestamps.
Declare shared behavior with trait, then include it inside any class via use TraitName;. During compilation, PHP copies the trait's methods directly into the class as if you wrote them there.
<?php
declare(strict_types=1);
trait HasSlug
{
public function toSlug(string $title): string
{
$clean = strtolower(trim($title));
return preg_replace('/[^a-z0-9]+/', '-', $clean) ?? $clean;
}
}
class Lesson
{
use HasSlug;
public function __construct(public string $title) {}
}
$lesson = new Lesson('PHP Traits and Reuse');
echo $lesson->toSlug($lesson->title) . PHP_EOL;
If a class defines a method with the same name as a trait method, the class method wins. When two traits imported into the same class define conflicting method names, resolve the collision explicitly using insteadof and as.
<?php
trait JsonFormatter { public function format(): string { return '{}'; } }
trait CsvFormatter { public function format(): string { return 'a,b'; } }
class Exporter
{
use JsonFormatter, CsvFormatter {
JsonFormatter::format insteadof CsvFormatter;
CsvFormatter::format as formatCsv;
}
}
use Namespace\Class; with use TraitName;: use at the top of a file imports namespaces; use inside a class body attaches traits.new?No. Traits are horizontal code mixins, not standalone types, so new HasSlug() fails and $obj instanceof HasSlug is invalid.
Yes. Traits can compose other traits via use OtherTrait; inside the trait body.
abstract methods?Yes. Adding abstract public function getId(): int; inside a trait forces any class using that trait to implement getId().
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.