What are TRAITS in PHP ?

What are Trait in PHP ? Why do we need Trait in PHP ?

In this article we will be working on a very new feature which is introduced in PHP 5.4 which is Traits in PHP.
Traits are mechanisms which help and increase in code re-usability, and also serves perfectly to solve the problem of multiple inheritance in php.

For example we have two or more than two classes that need to access a method / function .
So to solve this before version 5.4 you were suppose to do something like :

First of we create a Log class, which would be used to save log messages

Now we create another classes that will use  this feature of saving logs, but these classes can not extend our Log class as multiple inheritance does not exist in PHP:

Now we have to create object of log class again and again also we can not extend the log class in multiple classes therefor we will now move on to new feature of php that is traits and we will convert our Log class to a Trait. Now exactly you will come to know What are traits in php

And this is how we will use our Log Trait in our multiple classes:

Now we use the log() method directly without creating any instance of class and calling it in constructor function this is  because our multiple classes have accessed the characteristics (methods as well as  attributes) Log Trait.
If you have any questions please post below
You can check for Official documentation here:  http://php.net/traits

Leave a Reply

Your email address will not be published. Required fields are marked *