How Traits in PHP, Explanated with Example

How Traits in PHP, Explanated with Example

PHP 5.4 introduces the concept of traits. In PHP 5.4 version several new features was introduced, one such feature is PHP traits.

PHP traits help you to minimize code duplication in your codebase. Until the concept of traits, PHP uses classical inheritance model in which one class can inherit only one class. But sometimes, it is beneficial to inherit from multiple classes to avoid code duplication. To solve this problem, PHP community introduces the concept of traits.

PHP Traits

Trait allows us to reuse sets of methods freely in several independent classes living in different class hierarchies. In simple words, it gives you the flexibility to “copy and paste” code between classes.

trait Create {
 
    public function initiate($item){
              return  "item created";      
    }  
}
 
class some
{
   use Create;  // Calling trait
 
   public function status()
   {
        return "Job completed";
   }
 
}
 
   $demo = new Some;
   echo $demo->initiate("");
   echo $demo->status();

How PHP Traits Work

In the above example, I have created one trait create and used in a class some. When I created an object of some class, it can use the method initiate despite it is not being defined in some class.

Multiple Traits

We can use multiple traits in our class by listing them in use statement separated with a comma.

trait Create {
 
    public function initiate($item){
              return  "item created";      
    }  
}
 
trait Complete {
 
   public function message() {
          return "Completed";
   }
}
 
 
class some
{
   use Create, Complete;  // Calling multiple traits
 
}
NOTE – If two Traits insert a method with the same name, a fatal error is produced. If the conflict is not explicitly resolved.
trait Create {
 
    public function message(){
              return  "item created";
    }
}
 
trait Complete {
 
   public function message() {
          return "Completed";
   }
}
 
 
class some
{
   use Create, Complete;  // Calling multiple traits
 
}

Both traits (Create and Complete) has same method message. It will throw a fatal error if the conflict is not explicitly resolved.

PHP Fatal error:  Trait method message has not been applied, because there are collisions with other trait methods

To resolve this fatal error, we need to choose one of the conflicting methods using the insteadof operator.

trait Create {
 
    public function message(){
              return  "item created";
    }
}
 
trait Complete {
 
   public function message() {
          return "Completed";
   }
}
 
 
class some
{
   use Create, Complete {
           Create::message insteadof Complete;
          }
 
}

Traits Vs Interface – Difference between Traits and Interfaces

An Interface is a contract that says “this object is able to do this thing”, whereas a Trait is giving the object the ability to do the thing.

i) Using traits we can implement a method body while in an interface we can not provide a default implementation of a method body.

ii) We can implement multiple interfaces as well use traits in a class.

iii) An interface is used for Polymorphism(It means classes have different functionality while sharing a common interface), while we cannot use trait for Polymorphism.

 

Author Surjit Sidhu

Surjit SidhuSurjit is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling.