PHP 8.1 introduced support for enumerations. These enums are easy to use, but they offer extra features borrowed from object-oriented programming.
What Enumerations Do
Enumerations are useful when you want to work with a fixed set of related values. For example, you could use an enum to represent suits in a pack of cards or types of vehicle.
PHP’s enums are quite complex, with certain features borrowed from classes. You can use them in conjunction with type hinting to write more robust, predictable code.
Basic Enums
Enums typically store scalar values. These are analogous to C’s primitive data types, although PHP’s enums can store string values as well as integers. By default, however, PHP’s enumerated values have no scalar equivalent. They are known as basic enumerations:
Note how PHP reuses the case keyword that you’ll also encounter in switch statements. The values this enum represents are simply the names of the cases. You can refer to a specific enum value using this syntax:
For example, to refer to winter, use:
You can assign this value to a variable and test it against other Season values:
Using type hinting, you can restrict parameters or return types to a specific enumeration. This helps to avoid a whole set of errors and generally makes your code more maintainable:
If this get_current_season function tried to return something other than a Season, PHP would raise a fatal TypeError.
Backed Enums
PHP uses the term “backed enum” to refer to an enumeration with values. These can either be integers or strings:
You need to declare the type of a backed enum and it must be either int or string.
You can access the underlying value using the read-only value property:
When you use backed enums, you can also convert to them, from their equivalent scalar value, using the from method:
Enumeration Methods
PHP enums can also have methods, making them a bit like a cut-down class. This reflects PHP’s position as somewhere between a procedural language and an object-oriented one.
For example, you can add this simple method to the Month enum to fetch the number of days from a specific value:
Note that you can use $this to refer to a specific enum value, much like you use $this to refer to a specific object. You can also use the standard equality operator, ==, to compare enum values.
Enums also support static methods. You probably won’t have a lot of use for these, but they can be helpful if you need to write something that works like a constructor, for example:
Better Enumerate Than Never
Enumerations are a common feature of many languages, including PHP’s ancestor, C. They’re one of the major features of the 8.1 release, bringing the language up-to-speed with many of its competitors.
PHP already has many features that make it suitable for web development. As the language matures, it continues to borrow from others and innovate original features too.