PHP Traits
PHP Traits: Horizontal Code Reuse in Single-Inheritance PHP
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.
Creating and Using a Trait
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;
Resolving Collisions and Precedence Rules
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;
}
}
Common Mistakes to Avoid
- Turning traits into hidden dumping grounds: Overusing traits spreads state across five files and hides dependencies. If a feature needs constructor injection, use a regular service class instead.
- Confusing
use Namespace\Class;withuse TraitName;:useat the top of a file imports namespaces;useinside a class body attaches traits. - Defining conflicting default properties across two traits: Two traits cannot declare the same property name with different visibility or initial values in the same class.
Frequently Asked Questions
Can you instantiate a trait directly with new?
No. Traits are horizontal code mixins, not standalone types, so new HasSlug() fails and $obj instanceof HasSlug is invalid.
Can one trait use another trait?
Yes. Traits can compose other traits via use OtherTrait; inside the trait body.
Can a trait declare abstract methods?
Yes. Adding abstract public function getId(): int; inside a trait forces any class using that trait to implement getId().
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.