The languages like C++ and Python allow the maximum reusability of the code by allowing multiple inheritance of classes. Mixins is an alternative for increasing code re-usability in the languages that don’t support inheritance. Ruby and Ext JS 4 have Mixins to mix the functionality of one or more classes without using inheritance. We read about the introduction of Mixins to Ext JS 4. However, both the approaches of increasing code re-usability have their own problems. Multiple inheritance has issues like Diamond Problem and Mixins is a complex mechanism to code and manage.
PHP does not support multiple inheritance. So, it becomes difficult to avoid duplicity of the code. To eliminate this drawback, the concept of Traits is introduced in PHP 5.4. PHP has adopted Traits for increasing the code reusability. The concept of Traits is already being used in languages like Scala and Perl.
What are Traits?
Traits make it relatively simple to freely reuse the methods belonging to different unrelated class hierarchies. Traits are collections of methods that do not belong to an actual class. Since, a Trait is not an actual class so it is not possible to create an instance of a Trait. This implies that the methods of Traits cannot be called directly. So, how can we use Traits?
A Trait can be used by incorporating it into a real class.
A Trait can be a collection of other Traits, so one Trait can use one or more other traits.
Using Traits – Generalized Syntax
You can initialize a Trait with trait keyword. The body of the trait will contain the methods of the trait.
// Method code
// Method code
Your Trait is ready to be used in a class. Trait can be used in the class by using the use keyword.
// Use myTrait
The single statement “use myTrait” will allow you to call/access the methods of the trait from the object of the class.
[php]$obj = new myClass();
// Executing the method from trait
$obj-> traitMethod1 ();
$obj-> traitMethod2 (); [/php]
Thus, by using Trait into Class, you can access the methods defined in the Trait.
Traits vs Interfaces vs Mixins
Traits are an improvement to interfaces because traits not only include method definition but also the implementation. However, Traits do resemble Mixins in the sense that both involve defining common functionality which can be mixed or added into real classes.