Skip to main content

PHP - What are Traits?

A trait is a way to share methods between classes: you write the methods once, and any class that needs them can pull them in.

A trait can hold regular methods as well as abstract ones, and those methods may use any access modifier (public, private, or protected).

This makes traits a tool for code reuse, because several methods can be dropped freely into many different classes.


Define a Trait

Start with the trait keyword and then give the trait a name:

Trait syntax

The basic shape of a trait definition:

index.php
<?php
trait TraitName {
  // some code...
}
?>

Use the Trait

Inside a class, write the use keyword and the trait's name to bring the trait in.

The next example has a trait named message1 and a class named Welcome that uses it. As a result, every method from the trait is available in the class.

Tip: Any other class that needs msg1() can use message1 in the same way. You avoid duplicated code, since the same method never has to be declared again and again.

Example

Welcome uses a trait, so its objects can call the trait's method:

Prompt
Create a PHP trait message1 with a msg1() method that echoes a message. Create a Welcome class that uses the trait. Create an object and call msg1().
Output: PHP script

Using a trait in a class

How a class brings in a trait:

index.php
<?php
class MyClass {
  use TraitName;
}
?>

PHP - Two Classes and One Trait

Here, a single trait, message1, has three public methods, and two classes, Welcome and Welcome2, use it. Both classes get all three methods, but they don't have to call all of them: the code calls just one on Welcome and all three on Welcome2.

Example

The same trait serves two classes, which call different methods from it:

Prompt
Create a PHP trait message1 with three public methods msg1(), msg2(), and msg3(). Create Welcome and Welcome2 classes that both use the trait. Welcome uses only msg1(), while Welcome2 uses all three methods.
Output: PHP script

PHP - Using Multiple Traits

A class isn't limited to one trait. This example has two traits, message1 and message2, and two classes. Welcome uses only message1, while Welcome2 uses both, with a comma between the trait names.

Example

Welcome2 lists two traits, separated by a comma:

Prompt
Create two PHP traits message1 and message2 with msg1() and msg2() methods respectively. Create Welcome using only message1 and Welcome2 using both traits. Create objects and call the methods.
Output: PHP script