Home What is Trait and What is Use of Trait in PHP?

What is Trait and What is Use of Trait in PHP?

70 viewsPHP
0

The trait is introduced in PHP 5.4  to solve the problem of Multiple inheritances of object-oriented programming language. A trait is the same as a class but we can’t’ extents or implement but we can access all the featured of trait using PHP( use ) keyword. As we know in single inheritance class can only inherit from one other single class. In the case of trait, it enables a programmer to reuse sets of methods or function freely in several independent classes living in different class hierarchies.

Let Take and Example What is the trait in PHP?

<?php
   trait Reader{
      public function add($var1,$var2){
         return $var1+$var2;
      }
   }
   trait writer {
      public function multiplication($var1,$var2){
         return $var1*$var2;
      }
   }
   class File {
      use Reader;
      use writer;
      public function calculate($var1,$var2){
         echo "Ressult of addition:".$this->add($var1,$var2) ."\n";
         echo "Ressult of multiplication:".$this->multiplication($var1,$var2);
      }
   }
   $o = new File();
   $o->calculate(5,3);
?>

Output

Result of addition two numbers:8
Result of multiplication of two numbers:15

Hint: we always use “Use keyword” to access trait inside the class.

Changed status to publish