Home » PHP » PHP Traits
This tutorial helps you learn ways to use PHP Traits to share functionality across independent classes that are not in the same hierarchy.
Only single inheritance is supported by PHP. It implies a child class can inherit only from one single parent.
You can use OOP traits if a class needs to inherit multiple behaviors.
You can use PHP Traits to declare methods used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes. These methods can have any access modifier (private, public, or protected).
Trait keyword is used for declaring Traits:
<?php
trait TraitName {
// some code...
}
?>
You can use the use keyword for using a trait in a class:
<?php
class MyClass {
use TraitName;
}
?>
Example:
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
In the above example, we declare one trait: message1. Next, we create a class: Welcome. The trait is used by the class, and all the methods in the trait will be available in the class.
In case other classes need to use the msg1() function, then you just have to use the message1 trait in those classes. This way, you can reduce the code duplication as there is no need to redeclare the same method repeatedly.
Example:
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
trait message2 {
public function msg2() {
echo "OOP reduces 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();
?>
In this example, we declare two traits: message1 and message2. Next, two classes are created: Welcome and Welcome2. The message1 trait is used by the first class (Welcome), and the second class (Welcome2) will use both message1 and message2 traits (multiple traits are separated by comma).