Differences between Traits and Inheritance

Learn about the advantages and disadvantages of traits in comparison to inheritance.

Trait vs. inheritance

The following is a list of properties that make traits different from inheritance:

  • Traits use a form of inheritance known as horizontal inheritance. Here, the code from the trait is included in the classes in which it is used. This is similar to using require or include functions in the classes to include code from the outside.
  • In a trait, it is possible to put concrete (real) methods, abstract methods, properties, and even constants.
  • While the same class can use more than one trait, it can only inherit from one class.
  • Traits do not respect the visibility scope. That allows a trait’s methods to access private properties and methods in the class that uses them.

In the example below, the trait’s method changePriceByDollars() is allowed to interact with the private property $price.

Get hands-on with 1200+ tech skills courses.