PHP traits
24 July 2025 (Updated 24 July 2025)
On this page
What is a trait?
A Trait provides a way to reuse methods between different classes without the classes needing to have common ancestor classes.
Here’s an example trait:
<?php
trait TraitA {
public function sayHello() {
echo 'Hello';
}
}
trait TraitB {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld
{
use TraitA, TraitB; // A class can use multiple traits
public function sayHelloWorld() {
$this->sayHello();
echo ' ';
$this->sayWorld();
echo "!\n";
}
}
$myHelloWorld = new MyHelloWorld();
$myHelloWorld->sayHelloWorld();
?>
Trait methods take precedence over inherited methods. This means
- Suppose you have a class
CompanyUser
with a parent classUser
. User
defines agetDetails()
method whichCompanyUser
inherits.- But if
CompanyUser
uses aHasDetails
trait that also definesgetDetails()
, then thegetDetails()
method of theHasDetails()
trait takes precedence over that ofUser
.
Links
Tagged:
PHP