PHP Traits: Adding method without insert method into parent or child class
have you ever think to make method but you can use it in parent class or child class, and you want to call it in another class without making again or don’t want to initialing the source of method that you want to use in class.
In PHP the best way to handle that case is implement reuse code called traits.
What is Traits?
Traits are 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 us to reuse sets of methods freely in several independent classes living in different class hierarchies.
Why should we use that?
The purpose of the combination of Traits and classes is to reduce the complexity of our code and make it more simple and read able.
How to use Traits?
Trait is similar to a class, but only inteded to group functionality in a finegrained and consistent way. It’s not possible to instantiate a Trait on it’s own.
Example case
in this case i want to make a method to sanitize my class. but i want it only for Admin. In the normal case we will make method into the parent of class. it’s will looks fine when the parent is doesn’t have lot of methods or lines. Imagine you have a parent class who already have long of lines. It’s will messed up, right?
when we are use a trait, we can make it more simple than the above code. look at the below code.
method sanitize is only can be use in admin class. so it’s like we make some method and append it into admin class.
After you read this article i think you will interted to read more about traits, you could visit the php documentation to know more about this.
thankyou for watching my article.