PHP Traits

bazeng

Samuel K.M

Posted on October 28, 2021

PHP Traits

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
💖 đŸ’Ē 🙅 🚩
bazeng
Samuel K.M

Posted on October 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

TDD CRUD API
laravel TDD CRUD API

January 11, 2023

Interface for router
webdev Interface for router

November 12, 2022