PHP 8.1 is Getting Enumerations!

A deck of playing cards

The PHP RFC for enumerations just passed a 44-7 vote to be accepted as a new feature in the upcoming PHP 8.1 release!

Enumerations, also known as "enums", are a special data type that can only contain specific, predefined (or "enumerated") values. They behave somewhat similar to constants, in that their names can be referenced in code, but they allow for stronger typing.

The classic use case illustrated by the RFC is of an enum that defines different suits of playing cards:

enum Suit {
  case Hearts;
  case Diamonds;
  case Clubs;
  case Spades;
}

From the RFC:

This declaration creates a new enumerated type named Suit, which has four and only four legal values: Suit::Hearts, Suit::Diamonds, Suit::Clubs, and Suit::Spades. Variables may be assigned to one of those legal values. A function may be type checked against an enumerated type, in which case only values of that type may be passed.

function pick_a_card(Suit $suit) { ... }
 
$val = Suit::Diamonds;
 
pick_a_card($val);        // OK
pick_a_card(Suit::Clubs); // OK
pick_a_card('Spades');    // TypeError: pick_a_card(): Argument #1 ($suit)
                          // must be of type Suit, string given

Enums can do more than just that - check out the RFC for a list of examples and capabilities.

I'm personally super excited about this feature and can't wait to start using them in my projects!

What Do You Think?

About Colin O'Dell

Colin O'Dell

Colin O'Dell is a Lead Software Engineer at SeatGeek. In addition to being an active member of the PHP League and maintainer of the league/commonmark project, Colin is also a PHP docs contributor, conference speaker, and author of the PHP 7 Migration Guide.