Learn PHP Tutorial

PHP OOP – Traits


In PHP, a class can be inherited at a time by using extends keyword. PHP supports only a single inheritance. In single inheritance a class can inherit from only one other single class. So what about if you want to inherit multiple class at a time, that was not possible before PHP 5.4.

In PHP 5.4, Traits are introduced to fulfill the feature of multiple inheritance by allowing multiple behaviors in a single class.

Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have an access modifier i.e., public, private or protected.

Traits are declared with the ‘traits’ keyword. And to use the trait in a class, use the ‘use’ keyword.

Syntax:

<?php
trait Trait_name {
  // your code here...
}

class A {
  use Trait_name;
}
?>

Using Multiple Traits

<?php
   trait ProgramA{
      public function add($a,$b){
         return $a+$b;
      }
   }
   
   trait ProgramB {
      public function multiplication($a,$b){
         return $a*$b;
      }
   }
   
   class Program {
      use ProgramA;
      use ProgramB;
	  
      public function calculate($a,$b){
         echo "Result of addition:".$this->add($a,$b) ."\n";
         echo "Result of multiplication:".$this->multiplication($a,$b);
      }
   }
   $obj = new Program();
   $obj->calculate(5,3);
?>

#Output
Result of addition:8 
Result of multiplication:15

insteadof keyword

While calling multiple traits inside a class, it might have same function name defined in some traits. To overcome this problem you will have to use insteadof keyword.

Example:

<?php
   trait ProgramA{
      public function add($a,$b){
         return $a+$b;
      }
   }
   
   trait ProgramB {
      public function multiplication($a,$b){
         return $a*$b*5;
      }
   }
   
   trait ProgramC {
      public function multiplication($a,$b){
         return $a*$b;
      }
   }
   
   class Program {
      use ProgramA;
      use ProgramB, ProgramC{
          ProgramB::multiplication insteadof ProgramC;
      }
	  
      public function calculate($a,$b){
         echo "Result of addition:".$this->add($a,$b) ."\n";
         echo "Result of multiplication:".$this->multiplication($a,$b);
      }
   }
   $obj = new Program();
   $obj->calculate(5,3);
?>

#Output
Result of addition:8
Result of multiplication:75