In PHP, the trait is a method of code re-usability. Php is single inheritance programming language. So there is a limitation of code reusability due to single inheritance. Traits in PHP is basically a method of code reusability. Traits have a similar declaration like the class but it includes reusable functions. We write reusable functions in traits and then call them in different classes.
For Example:
<?php
trait test1
{
public function hello() //Function hello is the function defined in trait test1
{
echo "HeLLO WorLd !";
}
}
class Myclass //Declaring class where traits will be used
{
use test1; //Add trait
}
$obj = new Myclass ();
$obj->hello(); // Print HeLLO WorLd !
?>
So method defined in php trait can be called in different classes if a common method is required. Multiple traits can also be used in a single php class. Also one trait can be used in another trait like classes.
