PHP OOP - Traits
PHP - What are Traits?
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Traits allow you to reuse several methods freely in different classes, and are a mechanism for code reuse.
Define a Trait
A trait is defined with the
trait
keyword, followed by a name for the trait:
trait TraitName {
// some code...
}Use the Trait
To use a trait in a class, use the
use
keyword followed by the trait's name:
class MyClass {
use TraitName;
}In the following example, we define a trait: message1. Then, we create a class: Welcome. This class uses the trait, and all the methods in the trait will be available in the class:
Example
<?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();
?>
Try it Yourself »
Tip: If other classes need to use the msg1() function, simply use the message1 trait in those classes. This reduces code duplication, because there is no need to redeclare the same method over and over again.
PHP - Two Classes and One Trait
In the following example, we define one trait: message1. This trait contain three public methods. Then, we create two classes: Welcome and Welcome2. The Welcome and Welcome2 classes use the trait, and all the methods in the trait will be available in both classes. However, the Welcome class only uses one of the methods in the trait, while Welcome2 uses all three methods in the trait:
Example
<?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();
?>
Try it Yourself »
PHP - Using Multiple Traits
In the following example, we define two traits: message1 and message2. Then, we create two classes: Welcome and Welcome2. The first class (Welcome) uses the message1 trait, and the second class (Welcome2) uses both message1 and message2 traits (multiple traits are separated by comma):
Example
<?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();
?>
Try it Yourself »