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.

<?php
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.';
else
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 work with it.

How it used to be done

Prior to the addition of enumerations, this sort of functionality could be done is different ways, but a common one was with the use of defined constants.

<?php
define('VehicleTypeSports','S');
define('VehicleTypeUtility','U');
define('VehicleTypeVan','V');
define('VehicleTypeSedan', 'C');
define('VehicleTypeMotorbike','B');

$vehicle_type = VehicleTypeSports; // S

if( $vehicle_type == VehicleTypeMotorbike )
echo 'Vehicle is a motorbike.';
else
echo 'Vehicle is not a motorbike.';

It’s not that different really but one of the issues that could occur with this sort of setup was that you couldn’t assign a type to the defined values, it was always a string.

So if you made a mistake and had something like this

<?php
$vehicle_type = VehicleTypeSprts;

Due to the spelling mistake, the vehicle_type variable will end up containing the string of ‘VehicleTypeSprts’ which could well mess up your code or cause issues saving data to a database, etc.

It would issue a warning:

Warning: Use of undefined constant

But it would continue with execution after setting the variable to the incorrect string value.

When using an enum, a mistake would issue an error and stop script execution (unless handled sufficiently with error handling).

Fatal error: Uncaught Error: Undefined constant VehicleType::Sprts

So not only does it provide easier to read code as well as defined types but it helps to avoid unintentional mistakes.

--

--

Tim Wells

Self taught software developer and photographer.