CodeBlanks Logo Icon CodeBlanks

Enums

PHP course · Expert · Lesson 37/54

Learn to define and use type-safe constants with enum.

Type-safe constants with enum

PHP 8.1 introduced enum to define a fixed set of values in a type-safe way. A Suit enum can list card suit names; it makes invalid values impossible.

Each case represents one value and stands for a singleton instance. Suit::Heart always returns the same object.

A parameter typed as Suit accepts only the four valid values; anything else fails at compile time or runtime.

Backed enum and enum methods

An enum can carry an int or string backed value: enum Status: int { case Active = 1; }. The int here is a scalar type; with PHP 8.0 union types parameters can also take combined types like int|string.

Backed enums expose Status::Active->value to read the value and Status::from(1) to build a case from a value.

An enum can also hold methods; a match expression inside picks behavior per case, so logic stays bound to state.

Exercise Suit backed enum

Define a string backed enum called Suit. Cases: Heart = "H", Diamond = "D", Club = "C", Spade = "S".

The echo line below should print H.

Show example solution
enum Suit: string {
  case Heart = "H";
  case Diamond = "D";
  case Club = "C";
  case Spade = "S";
}

echo Suit::Heart->value;

Test yourself

  1. Complete the enum case

    enum Suit {
      case Heart;
      case Diamond;
      case ____;
      case Spade;
    }
    
    Show answer
    enum Suit {
      case Heart;
      case Diamond;
      case Club;
      case Spade;
    }
    
  2. What does Status::Active->value return?

    enum Status: int {
      case Active = 1;
      case Paused = 2;
    }
    • Active
    • 1
    • Status
    • true
    Show answer

    1 — Correct. Since the Active case is backed by 1, ->value returns 1.

  3. Match the enum concepts

    enum
    typed constant set
    case
    enum member
    backed
    value-carrying enum
    ->value
    access backed value

All lessons in Expert