1 min read

PHP Traits

PHP only supports single inheritance: a child class can inherit only from one single parent. So, what if a class needs to inherit multiple behaviors? Traits solve this problem.

Traits are a mechanism for code reuse in single inheritance languages such as PHP. 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.


1. Defining a Trait

Traits are declared with the trait keyword.

trait message1 {
  public function msg1() {
    echo "OOP is fun! ";
  }
}

2. Using a Trait

To use a trait in a class, use the use keyword.

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();

3. Multiple Traits

A class can use multiple traits, separated by commas.

trait message2 {
  public function msg2() {
    echo "OOP reduces code duplication!";
  }
}

class Welcome2 {
  use message1, message2;
}

programming/php/php programming/php/php-classes