Member-only story

PHP Traits are useful

Atakan Demircioğlu
Stackademic

Traits in PHP are useful when sharing the functionality between classes without using inheritance.

In this post, I will try to explain the usefulness of Traits and provide a real-world example to show how they can cleanly solve common programming challenges.

What is a Trait in PHP?

A Trait in PHP is a mechanism for code reuse. It allows you to group methods and properties that can be included in different classes.

Unlike inheritance, which forces a strict parent-child relationship, the Traits let you inject reusable functionality into multiple classes, regardless of their place in the class hierarchy.

Why Use Traits?

  • Code reuse: Traits allow you to avoid duplicating methods and logic across classes.
  • Modular functionality: You can break complex functionality into reusable, maintainable pieces.
  • Solves the multiple inheritance (diamond problem): In multiple inheritance scenarios (which PHP doesn’t support), Traits are a safe way to reuse code.

Logging with Traits

Maybe this is the most common example that you can find. Let’s try to implement it together.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (5)

What are your thoughts?

I did not know it can be. Really appreciate for this info.

Php traits are similar to python decorators. Always enjoyied them for reusability