PHP | Short introduction to traits in PHP

Author - Parminder Kaur
3.02.2017
|
0 Comments
|

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.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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

Send your message