When to Use Traits in PHP? (With Examples)
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
Traits in PHP are a way of reusing code in languages like PHP which do not support multiple inheritance. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
You would use Traits when you want to share methods across unrelated classes. For instance, suppose you have methods that format output or handle data validation. These methods could be useful in many different classes. By putting these methods into a Trait, you can easily insert them into any class and use them.
Here’s an example of a trait:
trait MyTrait {
public function traitMethod() {
return 'I am a trait method';
}
}
Here’s how you would use this trait in a class:
class MyClass {
use MyTrait;
}
$myClass = new MyClass();
echo $myClass->traitMethod(); // outputs "I am a trait method"
You can use multiple traits in a single class:
trait TraitOne {
public function methodOne() {
return 'I am method one';
}
}
trait TraitTwo {
public function methodTwo() {
return 'I am method two';
}
}
class MyClass {
use TraitOne, TraitTwo;
}
$myClass = new MyClass();
echo $myClass->methodOne(); // outputs "I am method one"
echo $myClass->methodTwo(); // outputs "I am method two"
Traits can also define properties:
trait TraitWithProperty {
public $myProperty = 'I am a trait property';
}
class MyClass {
use TraitWithProperty;
}
$myClass = new MyClass();
echo $myClass->myProperty; // outputs "I am a trait property"
If two traits inserted into a class have a method with the same name, it will cause a fatal error. To avoid this, the insteadof
operator can be used to choose which one of the conflicting methods will be used:
trait TraitOne {
public function method() {
return 'I am method from TraitOne';
}
}
trait TraitTwo {
public function method() {
return 'I am method from TraitTwo';
}
}
class MyClass {
use TraitOne, TraitTwo {
TraitOne::method insteadof TraitTwo;
}
}
$myClass = new MyClass();
echo $myClass->method(); // outputs "I am method from TraitOne"
Please note that traits are a tool to be used sparingly. Overuse of traits can lead to confusing code, as it can be harder to trace where certain methods are coming from when they’re spread out across multiple traits. It’s generally a good idea to use traits only when methods need to be shared across several unrelated classes.