4 Reasons to use PHP Enums instead of old-fashioned class constants

Vlad Reshetylo
4 min readNov 7, 2023

--

Are you still using class constants in PHP, even though Enums were introduced two years ago? It’s time to discover the 4 compelling reasons to switch to PHP Enums.

1) Built-in “cases” method

Imagine you’re working on a project with different user statuses — some are active, some are banned, and others have unfinished registrations. In an old-fashioned way, you might handle these states with class constants, resulting in code like this:

But why is there an “all” method? Because it’s an extremely often case when you need a dropdown with all possible options. To achieve this, you can either create such a method or resort to using reflection.

Now, let’s see how Enums can simplify this:

With Enums, you have the built-in “cases” method, which automatically returns an array of all available options. Say goodbye to manually updating your common options list whenever a new status is added.

2) Type Hinting

Returning to the example with users’ statuses, let’s consider a case where we have a method for setting a user’s status. We want to have only valid statuses stored in the database. This is what it usually looks like:

It looks a little bit ugly. I wish we had a better solution… Wait a second, we have!

By type-hinting our method argument to expect an option from our UserStatus Enum, we remove the chance of having a bug here. Say goodbye to potential issues caused by invalid status values.

3) Enum methods

I will continue to use an example with users’ statuses. Let’s suppose that some of them are allowed to log in to the system, and some cannot.

How the logic could look in an old-fashioned way:

And how it can look with an enum

Yes, I agree, it’s not a “game changer”, but it makes your code cleaner and shorter

4) Uniqueness

This option slightly overlaps with a second point of this topic, but I want to highlight it separately.

Imagine, we have statuses not only for users but also for goods in our online shop.

Let’s take a code from our previous example and misuse it.

We will not get an error! It might not look like a big issue, but if in the future we change the value of ProductStatus::ACTIVE constant, we definitely will get an error here.

What about enums? Enums are unique.

Even if UserStatus::ACTIVE and ProductStatus::ACTIVE have the same value, it’s a different item. We can easily check that manually.

That means that type-hinting helps us here twice — it doesn’t allow the use of improper values and doesn’t allow the use of improper sources of those values, even if they look suitable.

That’s all for today; I hope you got to know smth new for yourself :)

--

--