PHP | Short introduction to traits in PHP

| By Webner

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *