PHP OOP – Traits

In PHP multiple inheritance is not supported, which implies a child class can only have one parent class.

Traits allow you to easily reuse methods across several classes that don’t have to be in the same hierarchy. Traits allow classes to reuse code horizontally, whereas inheritance allows reusing code vertically.

Methods that can be utilized across various classes are declared within the Trait class. In PHP, you can’t construct a Trait instance.

The trait keyword is used to declare traits, Use the use keyword to use a trait in a class:

Let’s see an example below:

<?php
trait MSG{
  public function msg1() {
    echo "Trait class object cannot be created! "; 
  }
}

class helo {
  use MSG;
}

$obj = new helo();
$obj->msg1();
?>

Multiple PHP Traits

Consider the following example using multiple traits:

<?php
   trait Add{
      public function add($var1,$var2){
         echo $var1+$var2;
      }
   }
   trait Multiply {
      public function multiplication($var1,$var2){
         echo $var1*$var2;
      }
      
      }
   
   class Calculate
   {
       use Add;
   }
   class Output {
      use Add;
      use Multiply;
   }
   $o = new Calculate();
   $o->add(5,3);
   echo "</br>";
// The Output class uses both traits so it can call the functions of both traits
$obj2 = new Output();
$obj2->add(6,5);
  echo "</br>";
$obj2->multiplication(4,5);
  
?>