Traits are reusable code blocks that can be mixed into any class — PHP's solution to the limitation of single inheritance.
trait HasTimestamps {
private string $createdAt;
private string $updatedAt;
public function touch(): void {
$this->updatedAt = date("Y-m-d H:i:s");
}
public function getUpdatedAt(): string {
return $this->updatedAt ?? "never";
}
}
trait SoftDeletes {
private bool $deleted = false;
public function delete(): void { $this->deleted = true; }
public function restore(): void { $this->deleted = false; }
public function isDeleted(): bool { return $this->deleted; }
}
class Post {
use HasTimestamps, SoftDeletes;
public function __construct(public string $title) {}
}
$post = new Post("Hello World");
$post->touch();
$post->delete();
echo $post->isDeleted() ? "deleted" : "active"; // deleted
trait A { public function hello(): string { return "A"; } }
trait B { public function hello(): string { return "B"; } }
class C {
use A, B {
A::hello insteadof B; // use A's version
B::hello as helloB; // keep B's as alias
}
}
$c = new C;
echo $c->hello(); // A
echo $c->helloB(); // B