One rule to write a perfect Trait in PHP
Published in
1 min readFeb 15, 2017
To begin, what are PHP Traits?
A PHP Trait is simply a lot of methods that you want include within another class.
A PHP Trait it’s a little bit like an abstract class but a Trait cannot be instantiated!
The “use” keyword must be declared in the top of your class to use the Trait.
For example (PHP 7 syntaxe):
trait Hello
{
public function hello() : string
{
return 'Hello';
}
}class Say
{
use Hello;
}(new Say)->hello(); // Hello
The important consideration
- A Trait is not a class!
- A Trait is not an abstract class!
- A Trait is not an interface!
In closing,
The only rule to write a perfect Trait in PHP is just to use it like a Mixin, without external dependencies! A Trait is philosophically self-sufficient!
A Trait can be used in any classes, abstract or not.