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:
<?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:
Output: PHP script
<?php
// Define a trait
trait message1 {
public function msg1() {
echo "PHP OOP is fun! ";
}
}
// Use the trait in a class
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
Using a trait in a class
How a class brings in a trait:
<?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:
Output: PHP script
<?php
trait message1 {
public function msg1() {
echo "PHP OOP is fun! ";
}
public function msg2() {
echo "Traits reduce code duplication! ";
}
public function msg3() {
echo "Hello World!";
}
}
class Welcome {
use message1;
}
class Welcome2 {
use message1;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
$obj2->msg3();
?>
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:
Output: PHP script
<?php
trait message1 {
public function msg1() {
echo "PHP OOP is fun! ";
}
}
trait message2 {
public function msg2() {
echo "Traits reduce code duplication!";
}
}
class Welcome {
use message1;
}
class Welcome2 {
use message1, message2;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>