Enums are a new feature in PHP 8.1 that allows you to define a custom type with a fixed set of values. Enums can help you write more readable and maintainable code by avoiding magic constants and ensuring type safety. In this tutorial, you will learn how to use enums in PHP 8.1 with practical examples.



What Are Enums?

An enum, short for enumeration, is a type that can only be instantiated with one of the predefined values. Each value is declared with the case keyword inside the enum definition. For example, you can create an enum to represent the days of the week:

enum DayOfWeek {
    case Monday;
    case Tuesday;
    case Wednesday;
    case Thursday;
    case Friday;
    case Saturday;
    case Sunday;
}

You can use the enum name and the double colon operator (::) to access the enum values. For example, you can assign an enum value to a variable or pass it as an argument to a function:

$today = DayOfWeek::Monday;
echo $today; // DayOfWeek::Monday

function isWeekend(DayOfWeek $day): bool {
    return $day === DayOfWeek::Saturday || $day === DayOfWeek::Sunday;
}

echo isWeekend($today); // false
echo isWeekend(DayOfWeek::Sunday); // true

Notice that you can use enums as type hints to ensure that only valid values are passed to a function or a class constructor. Enums are also compatible with the match expression, which can be used to perform different actions based on the enum value:

function getGreeting(DayOfWeek $day): string {
    return match ($day) {
        DayOfWeek::Monday => 'Happy Monday!',
        DayOfWeek::Friday => 'TGIF!',
        default => 'Have a nice day!',
    };
}

echo getGreeting($today); // Happy Monday!
echo getGreeting(DayOfWeek::Friday); // TGIF!

Pure vs. Backed Enums

Enums can be either pure or backed. A pure enum is an enum with no associated value other than its name. A backed enum is an enum that has a scalar value (either int or string) assigned to each case. You can declare a backed enum by specifying the type after the enum name and the value after the case name:

enum MonthOfYear: int {
    case January = 1;
    case February = 2;
    // ...
    case December = 12;
}

Backed enums are helpful when storing or serializing values in a database or a file. You can access the backed value using the value property on the enum instance:

$month = MonthOfYear::January;
echo $month->value; // 1

function getSeason(MonthOfYear $month): string {
    return match ($month->value) {
        3, 4, 5 => 'Spring',
        6, 7, 8 => 'Summer',
        9, 10, 11 => 'Autumn',
        default => 'Winter',
    };
}

echo getSeason($month); // Winter

Adding Methods and Constants to Enums

Enums can also have methods and constants, just like classes. You can define methods inside the enum definition using the public keyword. Methods can be either instance methods or static methods. Instance methods can use $this to refer to the current enum value, while static methods can use self to refer to the enum class:

enum Color: string {
    case Red = '#FF0000';
    case Green = '#00FF00';
    case Blue = '#0000FF';

    public function hex(): string {
        return $this->value;
    }

    public function rgb(): array {
        return sscanf($this->value, '#%02x%02x%02x');
    }

    public static function random(): self {
        return self::cases()[array_rand(self::cases())];
    }
}

You can call instance methods on enum values and static methods on enum names:

$color = Color::Red;
echo $color->hex(); // #FF0000
print_r($color->rgb()); // [255, 0, 0]

$randomColor = Color::random();
echo $randomColor; // Color::<some random color>

You can also define constants inside the enum definition using the const keyword. Constants can be used to store additional information related to the enum:

enum Planet {
    case Mercury;
    case Venus;
    case Earth;
    case Mars;
    case Jupiter;
    case Saturn;
    case Uranus;
    case Neptune;

    const GRAVITY = [
        self::Mercury => 3.7,
        self::Venus => 8.9,
        self::Earth => 9.8,
        self::Mars => 3.7,
        self::Jupiter => 24.8,
        self::Saturn => 10.4,
        self::Uranus => 8.9,
        self::Neptune => 11.2,
    ];
}

You can access constants using the enum name and the double colon operator:

$planet = Planet::Earth;
echo Planet::GRAVITY[$planet]; // 9.8

When to Use Enums?

Enums are a great way to represent a finite set of related values with a semantic meaning. Enums can improve the readability and maintainability of your code by avoiding magic constants and ensuring type safety. Enums can also help you avoid errors and bugs by preventing invalid values from being passed or assigned. Some examples of when you can use enums are:

  • Days of the week, months of the year, seasons, etc.
  • Colors, shapes, sizes, etc.
  • Statuses, states, modes, etc.
  • Directions, orientations, positions, etc.
  • Levels, ranks, grades, etc.
  • Options, flags, settings, etc.

Conclusion

In this tutorial, you learned how to use enums in PHP 8.1 with practical examples. You learned how to create pure and backed enums, how to access and compare enum values, how to add methods and constants to enums, and when to use enums in your code.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram