In this episode, we're digging into serializing and deserializing enums in PHP. At first, we revisit how we can easily get the raw value out of an enum and store it in the database (that's serialization). But the interesting part is going the other way—deserialization—which is all about taking that value from the database and converting it back into a proper enum case.
We walk through a hands-on example with a Book
class, showing how to grab the status (stored as a simple value in the database), and then, importantly, convert it back to an enum using the from
and tryFrom
methods. This lets us get a real enum case back instead of just a number or string, which makes our code cleaner and smarter. We also chat about what happens if the stored value doesn’t match any case—hint: tryFrom
is your friend here, as it can avoid errors by returning null
if there’s no match.
There’s also a little detour into API territory: if you JSON-encode a response containing an enum, PHP will actually give you the backing value. That can be both handy and surprising, so we see that in action too.
By the end, you’ll get why deserialization can be super useful, not just for the database but for any place where you want to turn plain values back into more meaningful, type-safe enums. Next up, we’ll see how you can get even more out of enums by adding custom methods—so if you’re still a bit fuzzy on this, stick around, it’ll all tie together soon!