Extending PHP 8.1 Enums

Steve Barbera
2 min readMar 10, 2022

--

Extending PHP Enums

The new PHP Enums are a fantastic new addition to PHP 8.1 feature set. They provide a helpful way of structuring data in your application. I’ve been recently working on a new Laravel project that utilizes Stripe and wanted a way to structure and reuse Stripe’s decline codes. Enums provided a perfect way structure the decline codes and also add some extended functionality of retrieving additional information.

Basic Setup

Let’s setup our Enum declaration with a partial list of the Stripe decline codes

Now let’s add a function inside the enum declaration called details()that contains the additional information about the decline codes as an array.

We can now call a enum case and get all of the details like so:

Let’s say you wanted to get a list of all the enum cases so that you can use them to build the options of input selection element. We can add a all() function. (I’m going to return this as a laravel collection).

Returning all of the decline codes as a collection is as easy as:

One final tip for you laravel users is you can use the $casts attribute in your models to cast your database fields using your enums.

You can then easily retrieve the details about decline code from the model.

This is my first time working with Enums and I’m really excited how functional and useful they are. Do you have any tricks or tips using enums? I would love to hear them.

Below is the complete enum declaration.

--

--

Steve Barbera
Steve Barbera

Written by Steve Barbera

Full Stack Developer, Electronic music enthusiast, occasional tweeter. stevebarbera.com

Responses (1)