Enums help you group related values under a single name. They make your code easier to read and less error-prone.
0
0
Enums in PHP
Introduction
When you have a fixed set of options, like days of the week or user roles.
When you want to avoid using plain strings or numbers that can cause mistakes.
When you want to check values easily and clearly in your code.
When you want to improve code readability by naming groups of constants.
When you want to use type safety to prevent invalid values.
Syntax
PHP
enum Name {
case Option1;
case Option2;
case Option3;
}Use the enum keyword followed by the enum name.
Each option is declared with case inside curly braces.
Examples
This enum defines three possible statuses for a process.
PHP
enum Status {
case Pending;
case Approved;
case Rejected;
}This enum lists four directions you can use in navigation.
PHP
enum Direction {
case North;
case South;
case East;
case West;
}This enum uses strings as values, useful for matching external data.
PHP
enum Size: string {
case Small = 'S';
case Medium = 'M';
case Large = 'L';
}Sample Program
This program defines a TrafficLight enum with three colors. The getAction function returns what to do for each color using a match expression. It then prints the actions for each light.
PHP
<?php
enum TrafficLight {
case Red;
case Yellow;
case Green;
}
function getAction(TrafficLight $light): string {
return match($light) {
TrafficLight::Red => 'Stop',
TrafficLight::Yellow => 'Get Ready',
TrafficLight::Green => 'Go',
};
}
echo getAction(TrafficLight::Red) . "\n";
echo getAction(TrafficLight::Yellow) . "\n";
echo getAction(TrafficLight::Green) . "\n";
OutputSuccess
Important Notes
Enums were introduced in PHP 8.1, so make sure your PHP version supports them.
You can add methods inside enums for extra behavior if needed.
Using enums helps prevent bugs caused by invalid values.
Summary
Enums group related constant values under one name.
They improve code clarity and safety by limiting possible values.
Use enums when you have fixed sets of options like states or categories.