OOP — Traits
6 min read Quiz at the end
Traits let you reuse code across multiple unrelated classes without inheritance. Define methods in a trait and mix them in with the use keyword. Traits are perfect for shared behaviour like logging and soft deletion.
Traits — Code Reuse
trait Timestamps {
private DateTime $createdAt;
private DateTime $updatedAt;
public function setCreated(): void {
$this->createdAt = new DateTime();
$this->updatedAt = new DateTime();
}
public function touch(): void {
$this->updatedAt = new DateTime();
}
public function getCreated(): string {
return $this->createdAt->format("Y-m-d H:i:s");
}
}
trait SoftDelete {
private ?DateTime $deletedAt = null;
public function delete(): void {
$this->deletedAt = new DateTime();
}
public function isDeleted(): bool {
return $this->deletedAt !== null;
}
}
class Post {
use Timestamps, SoftDelete;
public function __construct(public string $title) {
$this->setCreated();
}
}
$post = new Post("Hello World");
echo $post->getCreated();