Traits in php

In the last lesson we learnt about static method and properties. Today i am going to discuss about traits in php.

What is Traits ?

In PHP Traits are a mechanism of code inclusion or code re-usability. It is similar to (include, require). There might be a question striking in your mind that, we use inheritance for this purpose. Yes, you are thinking right. But there are some advantages of using traits over inheritance.

Since we know well that PHP supports only single inheritance means a class can only inherit a parent class only once. You can not inherit more than one classes in a child class.

While you can use more than one traits in a class. Let’s see how it works.


Declaration of Traits

we use trait keyword for declaration as we do class for class name declaration.


The below given example will demonstrate you how we use traits as code reuse and multiple code inclusion in place of inheritance. We have used priceConverter as trait name and method name changePrice.

We use keyword use to inherit traits method and properties.

Output : 3 dollar converted in indian rupees = 210

In the above example we have used only one trait priceConverter and as i told earlier that we can use more than one train in a class. So let’s take an example to prove this. In the below example i took two trait named country and priceConverter.

Output :
Country name is India
3 dollar converted in indian rupees = 210

Similarly you can use multiple traits as many you required,

Leave a Reply

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