PHP 8.1 introduced us to Enums, which are a way of managing fixed sets of values in an easy manner. Up until Enums existed, the standards for managing these fixed sets ranged from using constants to even using strings, both of which leave plenty of room for errors and make code harder to maintain.
Enumerations in short called "Enums", allow you to define a set of named values that a variable may hold. In PHP, there are two types of Enums: Pure Enums and Backed Enums.
Let’s start with pure Enums. Here’s an example:
enum Status {
case Active;
case Inactive;
case Pending;
}
In this example, Status
is a pure Enum with three possible values: Active
, Inactive
, and Pending
. It’s a clean way to represent different statuses in your application.
function updateStatus(Status $status): void {
if ($status === Status::Active) {
echo "User is active";
}
}
updateStatus(Status::Active); // Outputs: User is active
In the code above, the function updateStatus
takes a Status
Enum as an argument. It checks if the status is Active
and prints a message.
Now, let’s look at backed Enums. These are more flexible because each case has an associated value:
enum PaymentStatus: string {
case Paid = 'paid';
case Pending = 'pending';
case Failed = 'failed';
}
Here, PaymentStatus
is a backed Enum with string values. Each status (Paid, Pending, Failed) is linked to a specific string.
In this example, the function getStatusMessage
takes a PaymentStatus
Enum and returns a corresponding message. This is a clear and concise way to handle different payment statuses.
function getStatusMessage(PaymentStatus $status): string {
return match($status) {
PaymentStatus::Paid => 'Payment Completed',
PaymentStatus::Pending => 'Payment Pending',
PaymentStatus::Failed => 'Payment Failed',
};
}
echo getStatusMessage(PaymentStatus::Paid); // Outputs: Payment Completed
We can also add methods in Enums, see below code;
enum OrderStatus {
case Placed;
case Shipped;
case Delivered;
case Cancelled;
public function isFinalStatus(): bool {
return match($this) {
self::Delivered, self::Cancelled => true,
default => false,
};
}
}
// Usage
$status = OrderStatus::Delivered;
echo $status->isFinalStatus(); // Outputs: 1 (true)
Here’s why Enums are a game-changer in PHP:
Enums are a great way to make your PHP code more reliable and easier to understand. They reduce errors, improve readability, and simplify maintenance. If you’re using PHP 8.1 or later, start using Enums to make your projects cleaner and more efficient.
For more details, check out the PHP 8.1 release notes.
Enums might seem like a small change, but they can make a big difference in your code quality. Give them a try and see how they can improve your next project!
Explore how to utilize Laravel's context for improved tracking and debugging. Enhance your application's insights and manage data more effectively.
No Spam. Only high quality content and updates of our products.
Join 20,000+ other creators in our community