PHP Traits: How to Create Traits and use in PHP with Examples

PHP Traits are the way to adapt multiple behaviors in a class. By default PHP only allows you to inherit functionality from a single parent only. Using traits we have multiple behaviors in a single class.

What are Traits in PHP

Out of the box in PHP a child class can only inherit from a single parent class.

But what if, we want to inherit multiple behaviors to a single child class?

In that case, we use Traits.

In PHP, Traits are to declare that a method can be used in multiple classes.

Using Traits we can create methods or abstract methods that we can use in multiple classes with any access modifier.

How to Use Traits in PHP

The Trait methods are declared by using trait keywords before their name.

Here is the syntax for it-

trait TraitName {
    //Code that goes there..
}

That is how we create traits. But what about using it?

To use a Trait in class we use use a keyword before its name and put it inside the class where we want to adapt this trait.

Here is the syntax for using traits in a class-

class NameOfMyClass{
    use TraitName;
}

Examples of Traits

Here is a simple example of How can we use Traits in PHP:

trait welcomeMessage{
    public function welcomeMsg() {
        echo "Howdy!"
    }
    
}

class Welcome {
    use welcomeMessage;
}

$showMessage = new Welcome();
$showMessage->welcomeMsg();

Use Multiple Traits

As I point out earlier in this tutorial we can use multiple traits inside a class.

Adding multiple traits is basically the whole point of using traits instead of inheriting from a class.

Here is how we can Create and use multiple traits-

trait welcomeMessage{
    public function welcomeMsg() {
        echo "Howdy!"
    }
    
}

trait goodbyeMessage{
    public function goodbyeMsg() {
        echo "Okay, Bye"
    }
    
}

class Greeting {
    use welcomeMessage, goodbyeMessage;
}

$showMessage = new Greeting();
$showMessage->welcomeMsg();

echo "<br>";

$showMessage2 = new Greeting2();
$showMessage2->goodbyeMsg();

Some important facts about Traits

  • We can use multiple traits in a class by adding trait names after using separated by commas.
  • Trait function can be Public, Private, or Protected.
  • To use a Trait we use the keyword use.
  • Traits are useful when we want to add the same behavior again and again in different classes and with different behavior as well.
  • We can add multiple functions inside traits.