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.

In This Article
Introduction
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
1 2 3 4 5 |
<?php trait TraitName { // some code... } ?> |
By using use keyword we declare trains into the class,
1 2 3 4 5 |
<?php class TestClass { use TraitName; } ?> |
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.
1 2 3 4 5 6 7 8 9 10 |
trait message1 { } trait message2 { } class Welcome { use message1, message2; } |
Example of Traits in PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php trait printMessage { public function callMessage() { echo "Traits are useful! "; } } class Testing { use printMessage; } $obj = new Testing(); $obj->callMessage(); ?> |
Output: Traits are useful!
Code Highlights:
- First we create
printMessage
trait and declared a functioncallMessage
()
inside the trait with print some text. - On next step we create a PHP class
Testing
and call traituse printMessage;
usinguse
keyword. - Now we create an object of a class and call the function which create inside the trait.
Conclusion
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:
- Increase PHPMyAdmin Import Size Ubuntu and XAMPP
- Send Mail From Localhost in PHP Using XAMPP
- isset vs empty vs is_null in PHP With Example
- Save contact form data in CSV file using PHP
Happy Coding..!
One thought on “What are Traits in PHP And Its Use With Example”