In this episode, we dive back into the backed enum we created earlier, which had values like 1, 2, and 3 for different book reading statuses. While having just those values is nice, by themselves they're not super helpful for output—especially if you want to display something user-friendly in your UI or API responses.
So, we're going to add a method to our enum (we call it presentTense
), which will return a string that's a lot more meaningful, like "wants to read," "is reading," or "has read," depending on the status. We use a PHP match
statement here, which is just a cleaner alternative to a bunch of if
or switch
statements. If you're new to enums, don't worry—we also show how you could do the same with good old if
statements.
We then walk through a real-world use case: imagine storing the enum value (like 1) in your database, pulling it out, converting it back into an enum object, and then calling this new method to get a human-readable string for your UI.
This approach not only makes your UI output a lot more useful, but it's also really helpful when building API responses, because you can now include user-friendly status descriptions directly in your JSON outputs. Finally, we share a little tip: you can reference the enum cases with self
to keep things nice and tidy.
By the end of the episode, you'll see how adding methods to enums can make your code way more expressive and cleaner, whether you're displaying info in a UI or sending it out via an API.