PHP Traits

Samuel K.M - Oct 28 '21 - - Dev Community

Traits

PHP allows single inheritance only, A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way.It can have all access modifiers.

You may ask yourself why would we need traits while we have Interfaces ?
The difference is interfaces only have abstract methods. A trait has methods that are abstract and also defined.

To declare a trait use the trait keyword.

<?php
trait Person{
  public function talk(){
    echo "Hello,call later ";
  }
  public function walk(){
    echo "I am driving";
  }

}

class Driver{
   use Person;
}

$driver = new Driver();
$driver->talk();
$driver->walk();
Enter fullscreen mode Exit fullscreen mode

Using Multiple Traits

<?php
trait Model {
    public function carModel() {
        echo 'Volvo ';
    }
}

trait Year {
    public function manufactureYear() {
        echo '2014';
    }
}

class DefineVehicle {
    use Model, Year;
    public function DescribeVehicle() {
        echo 'The Vehicle type is:';
    }
}

$car = new DefineVehicle();
$car->DescribeVehicle();
$car->carModel();
$car->manufactureYear();

?>
?>
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .