Categories
Code Area

Understanding of PHP Traits

As we know PHP is a single inheritance language, so what does it mean? It means one class can only inherit from another one class. So it doesn’t allow to inheriting from multiple class. But sometimes it’s might be beneficial to inherit from multiple classes.

To take care of this problem PHP introduced Traits in their 5.4 release. With the using traits, the developer can avoid the problems of multiple inheritances.

What is Traits:

Traits are something like a group or bundle of methods which you want to use within other classes. PHP introduced traits to reduce code duplication and overcome the limitations of single inheritance.

Using PHP Traits

From the above code snippet, you can see we have traits called Common and two different classes called Article and Comments.
Both Article and Comments use Common traits. So when a class uses any traits then all of the methods will available within that class. So the socialSharing() method of Common traits is now available within of these two classes.

In this way, you can reduce your code and avoid multiple inheritances.

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

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