0

While learning PHP I read about classes and interfaces, which I am familiar with.

And traits, which I am new to. It is described as separate modules made like abstract classes but using different inheritance approach: trait may be inherited from another trait, and included in a class.

I haven't seen this feature in other common OO languages before, so the question is:

  • Which role traits play in object-oriented design in PHP?
Ilya Tereschuk
  • 1,204
  • 1
  • 9
  • 21

1 Answers1

2

Sometimes two classes that have nothing in common (and thus don't share ancestry) can still benefit from code reuse.

Traits let you extract common functionality out of classes into traits and reuse it in other classes. They don't bear the semantical weight of inheritance.

For example, if you can post comments on Users and Articles, both of them can use the Commentable trait.

If such composition a good or a bad practice of object-oriented design, is a matter of hot debate.

Also, it's widely used in Ruby in form of modules.

Leonid Shevtsov
  • 14,024
  • 9
  • 51
  • 82