Avatar ·

How to properly implement enumerations (Enum) in PHP without built-in support?

Hello everyone! I'm a beginner PHP developer and I've run into a problem. In other languages (Java, C#) there is a convenient enum construct that allows you to define a fixed set of constants. For example, order statuses: "new", "processing", "shipped", "delivered".

\n\n

In PHP I haven't found a built-in enum. I tried using regular class constants:

\n\n
class OrderStatus {\n    const NEW = 'new';\n    const PROCESSING = 'processing';\n    const SHIPPED = 'shipped';\n    const DELIVERED = 'delivered';\n}\n\n$status = OrderStatus::NEW;\n
\n\n

But this is inconvenient. I cannot check that the $status variable contains only one of the allowed values. You can accidentally assign $status = 'invalid_status', and no error