What are Traits in PHP And Its Use With Example

Before we start with What are Traits in PHP and Its use, we have to know why PHP traits are developed. Traits are introduced in PHP 5.4 version which is completely easy to use and declare.

As we all know PHP Inheritance only supports single inheritance. When we go for multiple inheritance PHP doesn’t support it.

So, how we can take or reuse the functionality of other classes at once. To solve this problem PHP developed traits in PHP programming.

What are Traits in PHP And Its Use With Example


Here we start from basic PHP OOP (Object-oriented Programming), in the PHP OOP concept Traits are an essential part for the reuse of the functions on multiple classes which we are not able to do by using inheritance.

By using PHP traits we declare methods or functions which we reuse on multiple classes by using use keyword to declare it on classes.

Traits can have abstract methods and access modifiers like public, private, and protected.

Syntax of Traits

By using use keyword we declare trains into the class,

Points to Remember about Traits

  • Traits are use for decalre or create functions for reuse in multiple classes.
  • Traits support abstarct methods.
  • We can also apply access modifiers on traits.
  • To declare traits in classes we use “use” keyword.
  • We can declare multiple traits into the class.

We can declare multiple traits using a comma, see the example below, you can run it by using CMD also.

Example of Traits in PHP

Output: Traits are useful!

Code Highlights:

  1. First we create printMessage trait and declared a function callMessage() inside the trait with print some text.
  2. On next step we create a PHP class Testing and call trait use printMessage; using use keyword.
  3. Now we create an object of a class and call the function which create inside the trait.


In this article we discuss complete concept of about Traits, which is an OOP concept. Here you can find the complete explanation of trait with example.

I hope you understand the complete concept of traits. Please let the comment below if you face any issue.

To know more PHP: Traits – Manual.

Also Read:

Happy Coding..!

Was this article helpful?
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP.
Posts created 188

One thought on “What are Traits in PHP And Its Use With Example

Leave a Reply

Your email address will not be published.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top