Traits are a way to reuse method code in multiple classes without inheritance. They are defined using the trait
keyword and included in a class using use
. Traits help overcome PHP’s single inheritance limitation. You can use multiple traits in a class, and resolve method conflicts using insteadof
and as
. Traits promote clean, reusable OOP design.
1. Why Use Traits?
PHP doesn’t support multiple inheritance (a class can’t extend more than one class), but Traits solve this by allowing you to reuse method logic across multiple classes.
2. Basic Trait Example
trait Logger {
public function log($msg) {
echo "Log: " . $msg;
}
}
class User {
use Logger; // Include trait
public function create() {
$this->log("User created");
}
}
$user = new User();
$user->create(); // Output: Log: User created
File: trait_basic.php
3. Using Multiple Traits
trait A {
public function methodA() {
echo "A";
}
}
trait B {
public function methodB() {
echo "B";
}
}
class MyClass {
use A, B;
}
$obj = new MyClass();
$obj->methodA(); // Output: A
$obj->methodB(); // Output: B
File: multiple_traits.php
4. Trait Conflict Resolution
trait A {
public function test() {
echo "From A";
}
}
trait B {
public function test() {
echo "From B";
}
}
class Demo {
use A, B {
B::test insteadof A; // Use B's version
A::test as testA; // Alias A's version
}
}
$obj = new Demo();
$obj->test(); // Output: From B
$obj->testA(); // Output: From A
File: trait_conflict.php