Use PHP Traits Keyword Using OOPS

Basically trait is word use in biology. In php trait is method of code re-usability.As we know php is single inheritance programming language.As per my opinion main intention of introducing trait in php is to reduce limitation of code re-usability in PHP single inheritance nature.


PHP 5.0

2004 - Abstract classes and interfaces introduced

PHP 5.4

2012 - Traits introduced

Abstract Classes are in reality define things that are abstract e.g Vehicle is an abstract thing until or unless its materialized in the form of a car or a bike . Neither interface define it nor traits.

Interfaces compliment the class inheritance functionality where a class inherits from multiple classes(only certain languages provide multiple inheritance e.g C/C++). Interfaces , as names suggest focus on the INTERFACE , and not the implementation of the interface method in class which is implementing it. It makes classes PULG & PLAYABLE so everyone should follow a standard. If you further read about factory and adapter pattern on OOP you will understand it.

Traits have implementation/functionality that is not bound to specific classes.Instead it could be found across different classes. Its like a gene in genetics which stays mute in parents and appear only in certain children. Or to be concise selective inheritance but not bound to single class. So it provides a way much better code-reuse

Declaration of PHP Trait

  1. trait test_trait   
  2. {  
  4.     public  
  5.     function traittestFunction()   
  6.   {  
  7.         echo "This is callable by your class object";  
  8.     }  
  9. }  
Declaring class where traits will be used, 
  1. class helloTest   
  2. {  
  3.     use test_trait;  
  4. }  
  5. $objTest = new helloTest();  
  6. $objTest - > traittestFunction();  

This is callable by your class object.