PHP only supports single inheritance—a child class can inherit from only one parent. To overcome this limitation and allow developers to reuse methods freely across several independent classes, PHP introduced **Traits**.
A trait is a mechanism for code reuse in single inheritance languages. It is like a "mini-class" that contains methods you can "inject" into other classes. Traits are defined using the trait keyword.
<?php
trait Message {
public function msg1() {
echo "OOP is fun! ";
}
}
?>
To use a trait in a class, you use the use keyword inside the class body. Once used, all the methods of the trait become available in that class as if they were defined there.
<?php
trait Welcome {
public function sayHello() {
echo "Hello World! ";
}
}
class User {
use Welcome;
}
$obj = new User();
$obj->sayHello(); // Outputs: Hello World!
?>
User and a Post class might need a Logger trait).
A class can use more than one trait by listing them after the use keyword, separated by commas.
<?php
trait Trait1 {
public function msg1() { echo "Message 1 "; }
}
trait Trait2 {
public function msg2() { echo "Message 2 "; }
}
class MyClass {
use Trait1, Trait2;
}
$obj = new MyClass();
$obj->msg1();
$obj->msg2();
?>
When there are methods with the same name, PHP follows a specific order of priority (precedence):
Timestampable, Sluggable).