In this episode, we dive into how to define enums in PHP from scratch. We kick things off by creating our own enum called BookStatus
, which represents different reading states for a book like WantToRead
, Reading
, and Read
. You'll see how the enum syntax is similar to a class but instead of constants, we define "cases."
We experiment a bit by dumping out the enum values to the screen and see that each one is actually an object—a neat detail about enums in PHP! There’s a quick detour to confirm this with a classic is_object
check. The video also highlights a major benefit: enums give us a dedicated type that we can use for type-hinting in functions or methods. This makes our code less error-prone because you can’t accidentally pass in just any value—it has to be one of the enum's predefined statuses.
To wrap up, we try passing the enum through a mock fill
method (like you’d see in a framework model). This shows off how using enums makes your code more robust, since you get a type error if you try to pass a plain string instead of an enum case. Next time, we’ll check out backed enums, which take things further and are even more useful, especially for storing values in a database.