PHP Expert · Lesson 1 · On the house

Enums

Pure vs backed, cases, from/tryFrom, methods. Lesson 1 is free — on the house.

Lessons · PHP Expert · Lesson 1 of 10 · On the house

Enums

Pure vs backed, cases, from/tryFrom, methods.

Illustration for PHP
Lesson 1 is on the house.

PHP 8.1 enums are first-class types. A pure enum has cases with no scalar payload: enum Status { case Draft; case Live; }. A backed enum declares string or int and each case gets a unique value: enum Role: string { case Admin = "admin"; }.

Enum::cases() returns all cases in declaration order. Backed enums add from($value) (throws ValueError on miss) and tryFrom($value) (returns null on miss). Pure enums have neither — there is no backing value to parse.

Enums may declare methods and implement interfaces. Inside a method, $this is the current case; match ($this) is the idiomatic way to branch per case. Static methods on the enum type are allowed too.

Cases are singletons: Status::Draft === Status::Draft is true. You cannot new Status(). Compare with === or match on the case itself.

Misses: calling from on a pure enum, using duplicate backing values, or treating an enum case like a class you construct with new.

enums

<?php
enum Status {
    case Draft;
    case Live;

    public function label(): string {
        return match ($this) {
            self::Draft => "draft",
            self::Live => "live",
        };
    }
}

enum Role: string {
    case Admin = "admin";
    case Editor = "editor";
}

$s = Status::Draft;
echo $s->label() . "\n";
echo Role::from("admin")->value . "\n";
echo (Role::tryFrom("nope") === null ? "null" : "hit") . "\n";
echo count(Status::cases()) . "\n";
Match this when you type.

Quiz

What does Role::from("admin") return?

Quiz

What does tryFrom return when the value is unknown?

Quiz

Can a pure enum use from()?

Quiz

What does Status::cases() return in the still?

Check

Match the still for: Enums.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.