What are Enums in PHP 8.1, and why are they preferred over class constants for defining fixed sets of values?
Last updated
Enums (PHP 8.1) are a dedicated type for a fixed, finite set of named values, replacing loose class constants with a real type the engine and IDE can validate.
Two kinds:
Pure enums: cases with no scalar value (
enum Suit { case Hearts; }).Backed enums: each case maps to an
intorstring(enum Status: string { case Active = 'active'; }), withfrom()andtryFrom()helpers.
Why preferred over class constants:
Type safety: you can type-hint
Status $s, so only valid cases are accepted; a bareconstlets any matching string slip through.Each case is a singleton object, so identity comparison with
===is reliable.They can hold methods, implement interfaces, and use traits, keeping related behavior with the values.
cases()gives the full list for iteration/validation.
Caveat: Enums cannot have mutable state and cannot be instantiated with
new.
[lang:php]
enum Status: string {
case Active = 'active';
case Banned = 'banned';
public function label(): string {
return ucfirst($this->value);
}
}
function setStatus(Status $s): void {} // only valid cases accepted
Status::tryFrom('active'); // Status::Active or null
- https://en.wikipedia.org/wiki/PHP
- https://lemon.io/for-developers/php-developer-jobs/
- https://lan-portal.uob.edu.ly/visit/BOOK/529X432U02/modern-php_new__features_and_good-practices.pdf
- https://lan-portal.uob.edu.ly/upload/MD/D57953S372/modern-php__new_features_and__good__practices.pdf
- https://news.ycombinator.com/item?id=30786927
- https://kvnc-inc.medium.com/solid-principles-in-php-1c41069e9af6
- https://www.shkodenko.com/
- https://confoo.ca/en/2024/sessions