Traits in PHP


Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.


What was requirement to introduce traits

  1. Multiple inheritance.
  2. Not to force to override all methods.
  3. Can contains abstract methods and as well as body methods.
  4. Can be used together with inherits and implements.

Basically Traits are introduced to avoid some problems in case of inheritance, These are the common problems in class or interface

Problem in class:

In a traditional you are not allowed to create abstract methods and class can not be inherited by another class if it is inheriting any other class.

Problem in Abstract class:

In Abstract class you can create abstract method as well body methods but whenever a class will inherit this abstract class, it will have to define the body of all abstract methods of the abstract class. Also this abstract class can not be inherited by another class if it is inheriting any other class same as a normal class.

Problem in Interface:

By using interface you can achieve multiple inheritance in class in PHP but in an interface you are not allowed to define any body of a method. You can only have abstract methods and whenever you are going to implement this in a class, you have to define body of all methods.

Please follow and like us: