Enumerations, or enums for short, are a new feature in PHP 8.1. Enums are a way of representing a fixed number of values. Enums can be used to represent things like days of the week, months of the year, or even colors. Enums can make your code more readable and maintainable.
Enums can be thought of as a set of named constants. The values in an Enum must be unique and can be any scalar type (integer, float, string, or boolean). Enums are declared using the enum keyword.
Basic Syntax
Here’s what a simple enum looks like:
enum PostStatus {
case Published;
case InReview;
case Draft;
}
The case keyword, previously part of switch statements, is used to delineate the specific values the enum accepts. Values are referenced in the same way as class constants:
$published = PostStatus::Published;
▶ Enums in PHP 8.1 with Practical Examples.
Top comments (0)