PHP — Traits
Basic trait
<?php
trait Timestampable {
private string $createdAt;
private string $updatedAt;
public function setCreatedAt(): void {
$this->createdAt = date('Y-m-d H:i:s');
}
public function getCreatedAt(): string {
return $this->createdAt ?? '';
}
}
class Post {
use Timestampable;
public function __construct(public string $title) {
$this->setCreatedAt();
}
}
$post = new Post("Hello");
echo $post->getCreatedAt();
?>
Multiple traits
<?php
trait Loggable {
public function log(string $message): void {
echo "[LOG] $message\n";
}
}
trait Cacheable {
private array $cache = [];
public function cache(string $key, mixed $value): void {
$this->cache[$key] = $value;
}
public function getCache(string $key): mixed {
return $this->cache[$key] ?? null;
}
}
class User {
use Loggable, Cacheable;
}
$user = new User();
$user->log("User created");
$user->cache("name", "Alice");
echo $user->getCache("name");
?>
Trait conflict resolution
<?php
trait A {
public function show(): void { echo "A\n"; }
}
trait B {
public function show(): void { echo "B\n"; }
}
class MyClass {
use A, B {
B::show insteadof A;
A::show as showA;
}
}
$obj = new MyClass();
$obj->show(); // B
$obj->showA(); // A
?>
Abstract methods in traits
<?php
trait Validator {
abstract public function validate(): bool;
public function isValid(): bool {
return $this->validate();
}
}
class User {
use Validator;
public function __construct(private string $name) {}
public function validate(): bool {
return !empty($this->name);
}
}
$user = new User("Alice");
echo $user->isValid() ? "Valid" : "Invalid";
?>
Mini Practice
Write PHP code that:
- Creates a trait with methods
- Uses multiple traits in one class
- Resolves trait conflicts
- Uses abstract methods in a trait
Up Next
In the next lesson, you'll learn about Error Handling — exceptions in PHP.
Related Topics
Frequently Asked Questions about Traits
What is Traits in PHP?
Traits is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Traits?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Traits.
Why is Traits important in PHP?
Traits is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.