Coding for the web

Enumerations in PHP 8.1

How to use the new enumerations types in PHP 8.1

Tim Wells
2 min readFeb 15, 2023


Enumerations is something that has long been lacking in PHP in my opinion. Developers would use constants and defines to simulate similar functionality to enumerations, but that in itself came with it’s own set of challenges.

Apparently now, PHP 8.1 has introduced enumerations as a native value type. Be aware that this will not work in earlier versions of PHP, so before updating code that uses it, make sure your production system is running PHP 8.1 to problems.

Photo by Luca Bravo on Unsplash

How to define enumerations

Let’s say we’re dealing with vehicles and we want to use an enumeration to store the types of vehicles we might be dealing with.

enum VehicleType: string {
case Sports = 'S';
case Utility = 'U';
case Van = 'V';
case Sedan = 'C';
case MotorBike = 'B';

$vehicle_type = VehicleType::Sports; // S

// Check if the vehicle type is a motorbike
if( $vehicle_type == VehicleType::MotorBike )
echo 'Vehicle is a motorbike.';
echo 'Vehicle is not a motorbike.';

This sort of use for enumerations can make the code very easy to read, both for yourself when you come back to it later and for other developers that might need to…