Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Enumerations in PHP
Enumerations in PHP provide a way to define a fixed set of named constants, making your code more readable and preventing invalid values. While older PHP versions required workarounds, PHP 8.1 introduced native enum support.
Native Enums (PHP 8.1+)
PHP 8.1 introduced true enumeration support with the enum keyword
<?php
enum Status {
case PENDING;
case APPROVED;
case REJECTED;
}
function processOrder(Status $status) {
echo "Order status: " . $status->name . "<br>";
}
processOrder(Status::PENDING);
processOrder(Status::APPROVED);
?>
Order status: PENDING Order status: APPROVED
Backed Enums
Backed enums allow you to assign specific values to enum cases
<?php
enum Priority: int {
case LOW = 1;
case MEDIUM = 2;
case HIGH = 3;
}
echo "Priority value: " . Priority::HIGH->value . "<br>";
echo "Priority name: " . Priority::HIGH->name . "<br>";
// Convert from value back to enum
$priority = Priority::from(2);
echo "From value 2: " . $priority->name . "<br>";
?>
Priority value: 3 Priority name: HIGH From value 2: MEDIUM
Legacy Approach: Using Abstract Classes
For PHP versions before 8.1, you can simulate enums using abstract classes
<?php
abstract class Color {
const RED = "red";
const GREEN = "green";
const BLUE = "blue";
}
function setColor($color) {
echo "Setting color to: " . $color . "<br>";
}
setColor(Color::RED);
setColor(Color::BLUE);
?>
Setting color to: red Setting color to: blue
Comparison
| Feature | Native Enums (PHP 8.1+) | Abstract Classes |
|---|---|---|
| Type Safety | Yes | No |
| Value Validation | Automatic | Manual |
| Methods Support | Yes | Limited |
Conclusion
PHP 8.1+ native enums provide type safety and built-in validation, making them the preferred choice for modern PHP development. For legacy versions, abstract classes with constants offer a workable alternative.
Advertisements
