PHP 8 interview question · Most asked

What are enums in PHP 8.1? Explain pure vs backed enums.

Summary

Enums define a closed set of named values as a first-class type. Pure enums have only cases; backed enums map each case to a scalar int or string value.

Longer Answer

Enums replace class constants used as pseudo-enums, giving real type safety: a parameter typed Status can only receive a valid case. Each case is a singleton object, so === comparison works.

Backed enums (enum Status: string) give ->value, plus Status::from($v) (throws ValueError on unknown input) and Status::tryFrom($v) (returns null). They are ideal for database columns and API payloads. All enums get cases(). Enums can implement interfaces, have methods and constants, and use traits without properties, but cannot have state or be extended.

Code Example

<?php
enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';

    public function label(): string
    {
        return match ($this) {
            self::Pending => 'Awaiting payment',
            self::Paid => 'Paid',
            self::Shipped => 'On its way',
        };
    }
}

$status = OrderStatus::from($row['status']);
echo $status->label();
$maybe = OrderStatus::tryFrom('unknown'); // null

Key Points

  • Pure: enum Suit { case Hearts; }
  • Backed: enum Status: string { case Active = 'active'; }
  • from() throws, tryFrom() returns null
  • Cases are singletons; compare with ===
  • Enums can have methods and implement interfaces, but no properties

Explanation

What interviewers look for

The from/tryFrom distinction and using enums at system boundaries (DB, JSON) safely.

Common mistakes

  • Using from() on untrusted input without handling ValueError
  • Trying to add properties or instantiate an enum with new

Follow-up questions

  • How do you serialize an enum to JSON?
  • Can enums implement interfaces?

More most-asked PHP 8 questions

← All PHP 8 questions