Trait will be your best friend in your next project

Traits in  evolution, Traits were introduce in PHP 5.4, PHP is single inheritance language and not supporting multiple inheritance so it gives us in PHP multiple inheritance things.

So, when the classes living different class hierarchies need some similar methods, we can give the implementation of that method in the trait and those classes can use that trait. It means that we have defined the method only once in the trait and it could be reused in multiple classes from the different hierarchies .

We can define a trait just like we define a class, the only difference is that a trait keyword is used instead of a class. Method , properties and constants and their syntax will be same as we define in a class.​_

Lets dig into it.

So here is our trait “chargeable” with a method charge(). It is a good practice to define one trait per file , just like classes and inheritance definition , but here to give you a big and clear picture of what’s going on..

I am doing everything in one file. This is my base class “toy” and this is the sub class “ElectricCarToy” that is extending toy class. A “use” keyword is used to use a trait in a class. haha.. to many use word in one sentence. Let’s make it simple. This is the syntax to use trait in a class and it is written inside the class definition. Now everything that is in the Chargeable trait is now part of this class

Now we create an object of ElectricToy car class. Now we can see that this object is calling trait method just like it can its own class method or its parent class method.

Sharing is caring!

Related Post