trait, use)A trait is a mechanism for code reuse in single-inheritance languages like PHP. Traits allow developers to reuse sets of methods freely across independent classes without requiring class inheritance hierarchies.
flowchart TD
A["trait Timestampable"] --> B["User Class (use Timestampable;)"]
A --> C["Product Class (use Timestampable;)"]
A --> D["Order Class (use Timestampable;)"]
B & C & D --> E["All Classes Gain CreatedAt / UpdatedAt Behavior!"]
<?php
declare(strict_types=1);
trait Timestampable
{
public string $createdAt;
public string $updatedAt;
public function initializeTimestamps(): void
{
$now = date('Y-m-d H:i:s');
$this->createdAt = $now;
$this->updatedAt = $now;
}
public function touch(): void
{
$this->updatedAt = date('Y-m-d H:i:s');
}
}
trait Sluggable
{
public function generateSlug(string $title): string
{
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title), '-'));
}
}
class Article
{
use Timestampable, Sluggable; // Using multiple traits
public string $slug;
public function __construct(public string $title)
{
$this->initializeTimestamps();
$this->slug = $this->generateSlug($title);
}
}
$article = new Article("Mastering Modern PHP 8 Traits!");
echo "Article Slug: {$article->slug}
";
echo "Created At: {$article->createdAt}
";
insteadof or as aliasing syntax if two traits declare identical method names.Write a trait LoggerTrait with a method log(string $msg) that echoes "[LOG]: $msg", and include it in a class using use LoggerTrait;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.