sajad torkamani

What is a trait?

A Trait provides a way to reuse methods between different classes without the classes needing to have common ancestor classes.

Here’s an example trait:

<?php

trait TraitA {
    public function sayHello() {
        echo 'Hello';
    }
}

trait TraitB {
    public function sayWorld() {
        echo 'World';
    }
}

class MyHelloWorld
{
    use TraitA, TraitB; // A class can use multiple traits

    public function sayHelloWorld() {
        $this->sayHello();
        echo ' ';
        $this->sayWorld();
        echo "!\n";
    }
}

$myHelloWorld = new MyHelloWorld();
$myHelloWorld->sayHelloWorld();

?>

Trait methods take precedence over inherited methods. This means

  • Suppose you have a class CompanyUser with a parent class User.
  • User defines a getDetails() method which CompanyUser inherits.
  • But if CompanyUser uses a HasDetails trait that also defines getDetails(), then the getDetails() method of the HasDetails() trait takes precedence over that of User.

Links

Tagged: PHP