DEV Community

Cover image for What Is Trait In PHP?
Mohammad ALi Abd Alwahed
Mohammad ALi Abd Alwahed

Posted on

What Is Trait In PHP?

Question asked in every interview: What does trait mean in PHP?
Today's post is about PHP in general and specifically about something we use every day without delving deep into it, which is the trait class. We all know about object-oriented programming and how we can inherit from one class to another. However, sometimes we need to implement multiple inheritance, which means allowing a class to inherit from more than one class. Unfortunately, this feature is not supported in PHP, so we use traits instead.
In the image below, there is an example comparing traits in PHP and the same concept in Python.
In Laravel, all you need to do to use a trait is to start the class definition with the keyword "trait" and import the namespace "App\Traits." Apart from its main purpose, which is solving the problem of multiple inheritances, traits have many other uses, such as in SOLID principles, object-oriented programming, and more.

Image description

Top comments (0)