Traits
In a single inheritance language such as PHP, we often feel that we could have extended another class to inherit some functionalities. For example, in our Car
class, we have inherited all the generic vehicle functionalities and now we might be in need of adding some e-commerce functionalities. Again, the Motorcycle
class might want to have such e-commerce functionalities. As e-commerce related methods do not belong to the Vehicle
class, we need to think of an alternative approach to reuse such e-commerce behavior. Hence, when we need to add a group of behaviors to our objects, we group the behaviors in terms of methods with a trait
and use the trait
inside our classes. A trait is similar to a class but you can't instantiate it; rather, you can use traits inside classes. A trait can be used in a class context with the use
keyword; for example, use TraitName
.
Check out the following trait
syntax:
trait MyTraitName{ Â Â Â Â function one() Â Â ...