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.
Introduction
Here we will start with basic PHP OOP (Object-oriented Programming), in the PHP OOP concept Traits are an essential part of 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 in 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 used for declare or create functions for reuse in multiple classes.
- Traits support abstract methods.
- We can also apply access modifiers on traits.
- To declare traits in classes we use “
use
” keyword. - We can declare multiple traits in 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(); ?> |
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 creates inside the trait.
Conclusion
In this article, we will discuss the complete concept of Traits, which is an OOP concept. Here you can find the complete explanation of trait with examples.
I hope you understand the complete concept of traits. Please let the comment below if you face any issues.
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..!
[…] What are Traits in PHP And Its Use With Example […]