PHP Traits

PHP Traits

PHP only supports single inheritance: a child class can inherit only from one single parent.

So, what happens if a class needs to inherit multiple behaviors from completely different logic trees? This is where Traits come to the rescue!


The trait and use Keywords

Traits are used to declare methods that can be used in multiple classes, bypassing the single inheritance limit. Traits can have both methods and abstract methods, and they can be used across multiple classes, and their access modifiers (public, private, or protected) can be changed.

Traits are declared with the trait keyword, and included inside classes with the use keyword.

Trait Example

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

class Welcome { use message1; }

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

Multiple Traits

You can use multiple traits in a single class by separating them with commas.

use Trait1, Trait2, Trait3;