PHP Tutorial · Object-Oriented PHP · Lesson 33 of 38
PHP Traits and Static Members
Reuse methods with traits and use class-level static properties and methods.
Traits
A trait is a bundle of methods you can use in several unrelated classes — horizontal code reuse without inheritance:
<?php
trait HasTimestamps
{
private ?string $updatedAt = null;
public function touch(string $when): static
{
$this->updatedAt = $when;
return $this;
}
public function updatedAt(): ?string
{
return $this->updatedAt;
}
}
class Post { use HasTimestamps; }
class Comment { use HasTimestamps; }
echo (new Post())->touch("2026-10-12")->updatedAt(), "\n";
var_dump((new Comment())->updatedAt());
Output
2026-10-12 NULL
Static properties and methods
static members belong to the class, not to an object. Access them with ClassName:: or self:: / static:: inside the class. Common uses: counters, factory methods and constants.
<?php
class Order
{
public const STATUS_NEW = "new";
private static int $created = 0;
private function __construct(public readonly int $id, public readonly string $status) {}
public static function create(): static
{
self::$created++;
return new static(self::$created, self::STATUS_NEW);
}
public static function count(): int
{
return self::$created;
}
}
$a = Order::create();
$b = Order::create();
echo "Order #{$b->id} is {$b->status}; total created: ", Order::count(), "\n";
Output
Order #2 is new; total created: 2
Use static state sparingly — it's global state in disguise and makes testing harder.
Test yourself
Which keyword pulls a trait into a class?
includeextendsuseimplements
Show answer
Answer: use