MakeUseOf logo

How to Use Enums in PHP 8

A wooden tray containing wooden blocks with the names of the months inked on.
https://unsplash.com/photos/bv1dhsjeWbk
A technology enthusiast, Bobby studied Computer Science at the University of Southampton before working in a number of roles across industries, from the private sector to the charitable one, at multinationals and startups. He’s helped maintain backend Java servers, designed databases and front-end interfaces, and created a bespoke content management system.

Bobby also enjoys video gaming, and has written for several outlets, including a stint as Editor-in-Chief at Switch Player Magazine and contributions to online magazine, SUPERJUMP. Bobby uses a Mac for day-to-day work and an Android phone for distractions.
Sign in to your MakeUseOf account

Enumerations (enums) are a data type you can use to store a value from a custom set. They’re perfect to represent the kind of options you might show in a drop-down list.

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:

enum Season
{
 case Spring;
 case Summer;
 case Autumn;
 case Winter;
}

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:

EnumTypeName::EnumField

For example, to refer to winter, use:

Season::Winter

You can assign this value to a variable and test it against other Season values:

$favorite = Season::Summer;
 
if ($favorite == get_current_season()) {
 echo "It's my favorite season!";
}

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:

function get_current_season(): Season
{
 $day = date("z");
 
 if ($day < 59 || $day > 333) return Season::Winter;
 if ($day < 151) return Season::Spring;
 if ($day < 243) return Season::Summer;
 if ($day < 334) return Season::Autumn;
}

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:

enum Month: int
{
 case Jan = 1;
 case Feb = 2;
 //...
}

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:

echo Month::Jan->value;

When you use backed enums, you can also convert to them, from their equivalent scalar value, using the from method:

var_dump(Month::from(2));

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: no leap-year handling! */
function daysInMonth(): int {
 if ($this == Month::Feb) return 28;
 if (in_array($this, array(Month::Apr, Month::Jun, Month::Sep, Month::Nov))) return 30;
 return 31;
}

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:

static function random(): Month {
 return Month::from(rand(1, count(Month::cases())));
}

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.

AltStyle によって変換されたページ (->オリジナル) /