Tools
Log in
English

Learn to codePHP

PHP composition, static, traits and enums

Based on PHP 8.3enum · PHP 8.1+match · PHP 8.0+

A post holds its author, uses a trait, an enum status and a static counter.

In one line

Composition means holding another object as a property and letting it do part of the work. static members belong to the class rather than to each object; a trait is a chunk of methods pasted into several classes; an enum is a type that allows only a fixed list of values.

Why you need it

If a post extended Author, you would be saying a post is an author, and every author method would leak into posts. Keeping the status as strings like 'draft', 'publish' and 'published' turns each typo into a hidden bug.

Hold the author as a property (composition), pin the status down with an enum, write the slug code once in a trait and use it wherever needed. Values that exist once per class, such as the number of posts made, go into static.

Everyday picture

Think of a library book. A book has an author; it is not an author (composition). Its loan status is a stamp with exactly three choices: available, on loan, lost (an enum). The total number of books goes on one board for the whole library, not inside each book (static).

Example code

main.php · 69 lines
<?phpdeclare(strict_types=1); enum Status: string{    case Draft = 'draft';    case Published = 'published';     public function label(): string    {        return match ($this) {            Status::Draft => 'not public yet',            Status::Published => 'visible to everyone',        };    }} trait HasSlug{    public function slug(): string    {        return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($this->title)), '-');    }} final class Author{    public function __construct(public readonly string $name)    {    }} final class Post{    use HasSlug;     private static int $created = 0;    public Status $status = Status::Draft;     public function __construct(public string $title, private Author $author)    {        self::$created++;    }     public static function created(): int    {        return self::$created;    }     public function publish(): void    {        $this->status = Status::Published;    }     public function byline(): string    {        return "{$this->title} by {$this->author->name}";    }} $mina = new Author('Mina');$a = new Post('Hello, PHP 8.3!', $mina);$b = new Post('Traits & Enums', $mina);$b->publish();echo $a->slug(), ' | ', $a->status->label(), "\n";echo $b->slug(), ' | ', $b->status->label(), "\n";echo $b->byline(), "\n";echo 'posts made: ', Post::created(), "\n";var_dump(Status::from('draft') === Status::Draft, Status::tryFrom('gone'));

When to use it

  • Use composition over inheritance when "has a" fits (a post has an author)
  • Use an enum when the possible values are a short fixed list (order status, membership level)
  • Use a trait when unrelated classes need the same methods
  • Use static for values and helpers that exist once per class, not once per object

A static property lives only for one request. PHP starts fresh on every request, so the count is back to 0 next time. Numbers that must survive between requests belong in a database or cache.

Common mistakes

Using $this inside a static method

A static method is called on the class, so there is no $this. Keep class-wide values in a static property and use self::$n.

Wrong

final class Counter{    private int $n = 0;     public static function bump(): void    {        $this->n++;    }} Counter::bump();

When you run itFatal error: Uncaught Error: Using $this when not in object context

Fixed

final class Counter{    private static int $n = 0;     public static function bump(): int    {        return ++self::$n;    }} Counter::bump();echo Counter::bump(), "\n";

When you run it2

Getting a parent object from a child call (self vs static)

self is fixed to the class where the line is written (Model). static follows the class that was actually called (User), which is called late static binding. Factory methods meant to be inherited use new static().

Wrong

class Model{    public static function create()    {        return new self();    }} class User extends Model{} echo get_class(User::create()), "\n";

When you run itModel

Fixed

class Model{    public static function create(): static    {        return new static();    }} class User extends Model{} echo get_class(User::create()), "\n";

When you run itUser

Comparing an enum case with a string

An enum case is an object, not a string, so === against a string is always false and the condition quietly fails. Compare cases with cases, or turn a string from the database into a case with Status::from() first.

Wrong

enum Status: string{    case Draft = 'draft';} $s = Status::Draft;var_dump($s === 'draft');

When you run itbool(false)

Fixed

enum Status: string{    case Draft = 'draft';} $s = Status::Draft;var_dump($s === Status::Draft, $s->value === 'draft');

When you run itbool(true) bool(true)

Check yourself

Question 1

With only the class part loaded, one post is created. What is Post::created()?

new Post('One', new Author('Ari'));echo Post::created(), "\n";

Show the answer

Answer: 2. 1 The static slot starts at 0 when the program starts, and one constructor run makes it 1. The constructor runs even though the object is not stored.

Question 2

Which arm does match take?

echo match ('1') {    1 => 'int',    '1' => 'string',}, "\n";

Show the answer

Answer: 2. string match compares with ===. The string '1' is not identical to the integer 1, so the second arm wins. With no matching arm it throws UnhandledMatchError, and it never falls through like switch.

Questions people ask

How do self:: and static:: differ?

self points to the class where the line is written; static points to the class that was actually called. Inherited factory methods use new static().

How do I compare an enum with a string from the database?

Enum cases are objects, so === against a string is always false. Convert with Status::from() or compare ->value.

Do static property values survive to the next request?

No. PHP starts fresh for every request, so static values reset. Keep lasting values in a database or cache.