typestar

Backed enums in PHP

An enum whose cases carry string values — and behavior of their own.

<?php
enum Status: string {
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';

    public function isLive(): bool {
        return $this === self::Published;
    }
}

$post = Status::from('published');
echo $post->name, " -> ", $post->value, "\n";
var_dump($post->isLive());

// tryFrom returns null for unknown values instead of throwing
echo Status::tryFrom('deleted')?->value ?? 'unknown', "\n";

How it works

  1. enum Status: string binds each case to a database-friendly value.
  2. Methods on the enum let a case answer questions like isLive.
  3. from throws on unknown input; tryFrom returns null instead.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
412
Tokens
87
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 3 of 3 in Null & errors, step 21 of 27 in Language basics.

← Previous Next →