Mastering Enums in PHP 8.1: A Practical Guide

Enums, short for “enumerations,” are a powerful and useful feature in PHP 8.1 that allow developers to define a set of named constants. They provide a way to explicitly define a fixed set of values that a variable can take on, which can help improve the readability and maintainability of code.

To use enums in PHP 8.1, you first need to define an enum class using the enum keyword. For example:

enum Color {
  RED,
  GREEN,
  BLUE
}

In this example, we have defined an enum class called Color with three constants: RED, GREEN, and BLUE. These constants can then be used like any other class constants,
by referencing them with the :: operator. For example:

$favoriteColor = Color::RED;
echo $favoriteColor; // Outputs "RED"

You can also define enum values with explicit values, like so:

enum Color {
  RED = '#ff0000',
  GREEN = '#00ff00',
  BLUE = '#0000ff'
}

In this case, the constants RED, GREEN, and BLUE will have the values #ff0000, #00ff00, and #0000ff respectively.

One useful feature of enums is that you can use them as the return type for a function or method. For example:

function getColor(): Color {
  return Color::RED;
}

echo getColor(); // Outputs "RED"

You can also use enums as type hints for function arguments:

function setColor(Color $color) {
  // ...
}

setColor(Color::RED); // Valid
setColor(Color::PURPLE); // Invalid, as PURPLE is not a defined constant in the Color enum

Enums also provide several useful methods for working with their values. For example, you can use the values() method to get an array of all the constants in an enum:

$colors = Color::values();
print_r($colors); // Outputs ["RED", "GREEN", "BLUE"]

You can also use the isValid() method to check if a given value is a valid constant in an enum:

$isValid = Color::isValid('RED'); // true
$isValid = Color::isValid('PURPLE'); // false

Finally, you can use the getName() method to get the name of a constant from its value:

$name = Color::getName('#00ff00'); // "GREEN"

In summary, enums are a powerful and useful tool in PHP 8.1 for defining a fixed set of values and improving the readability and maintainability of your code. Whether you’re using them as function return types, type hints, or simply as a way to define named constants, they can help you write cleaner, more expressive code.