What is traits in PHP?


In 5.4 PHP version trait is introduced to PHP object-oriented programming. A trait is like class however it is only for grouping methods in a fine-grained and reliable way. It isn't permitted to instantiate a trait on its own. Traits are introduced to PHP 5.4 to overcome the problems of single inheritance. As we know in single inheritance class can only inherit from one other single class. In the case of trait, it enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

Example

<?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) .">br<";
         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

Explanation

In the above example, we have implemented a function from two traits in a single class. Due to trait, we are able to access multiple functions in a single class.

Note

We are using the "USE" keyword to access traits inside a class.

Updated on: 08-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements