Sometimes we need to inject common properties to a set of class, so most of the programmer add that properties in inherited class,
but the real problem comes when
- all or some of the classes have different parent class(inheritance)!
- code does not fit well in inheritance hierarchy.
Here trait comes to rescue our problem, as we all know that php does not support multiple inheritance,
so from php 5.4 we can use trait to reuse the sets of method in multiple independent classes.
Here in this article we will discuss the use of traits in php to overcome the problem of multiple inheritance.
What is trait?
Traits is a mechanism for code reuse in single inheritance languages such as PHP. 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.
Use of trait
Here we will see a simple example of how to create trait, and how we can use common set of methods in multiple classes using Trait.
// In above example you can see that both classes (ClassOne and ClassTwo) both having different parent class inherited.
// To use our our common set of methods we will simply add trait using “use BundleClass” keyword in our class.
//use of traits
Congrats, you have successfully implemented powerfull feture of PHP. Keep Coding 🙂