PHP Enums reference
22 April 2024 (Updated 22 April 2024)
On this page
In a nutshell
PHP enums allow you to define a custom type that’s limited to one of a discrete number of possible values.
Enums are a common feature of many programming languages. In PHP, enums are an instance of the Enum
class and can be either “pure” or “backed”.
Pure enums
A “pure” enum doesn’t associate any scalar values with any of the cases:
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
?>
Backed enums
A “backed” enum associates a scalar with all the enum cases:
<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
?>
Backed enums can be useful when you need to store values in a database or in an external system because they can be serialised/deserialized using their associated scalar value.
Backed enums implement the BackedEnum
interface, which exposes two additional methods:
from(int|string):
Returns the enum case corresponding to the scalar or throws aValueError
.tryFrom(int|string):
Returns the enum case corresponding to the scalar ornull
if not found.
Tagged:
PHP
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment