Trait

A Trait is simply a group of methods that you want include within another class. A Trait, like an abstract class, cannot be instantiated on itโ€™s own.

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

  • Multiple traits can be used by a single class.
  • A trait can declare a private variable.
  • Traits are able to be auto-loaded.
<?php
 trait A {
 public function hello() {
 return "PHP";
 }
 public function world() {
 return "Codez";
 }
 }
 
 class test{
 use A ;
 }
 
 $obj = new test();
 echo $obj->hello()."\n";
 echo $obj->world()."\n";
 
?>
Share

Leave a Reply

Your email address will not be published. Required fields are marked *