PHP Enums are underrated!

Honestly, PHP 8.1 was the best release of PHP since version 7.

The PHP Core team really nailed enums in PHP.

Most programming languages have enums, but many are just syntactic sugar around constants.

Most developers see enums as a place to store constants and move on. However, enums can do much more than that. Since enums can implement interfaces and contain functions, a lot more logic and validation can be achieved.

JSON Representation

Have you ever needed to ensure that frontend select fields match your backend select fields?

As far as I know, JsonSerializable is the only built-in interface that an enum can implement.

Different Data Types, Same Meaning

Sometimes your system integrates with another system that has a similar constant, but represents it in a different form.

Related Constants

It’s very likely you’ve run into a situation where one constant is related to another—for example, Roles & Permissions or SubscriptionType & ProductFeatures.

Type Safety (Probably the Most Important)

A language like PHP needs more type safety. Honestly.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *