PHP - Enums
In PHP 8.1 and later, Enums (Enumerations) were introduced as a way to represent a set of named values, which is useful for defining constants that can only take one of a predefined list of values.
Basic Enum Example
php<?php
enum Status {
case Active;
case Inactive;
case Pending;
}
// Usage
$status = Status::Active;
if ($status === Status::Active) {
echo "The status is active.";
}
In this example:
- The
enum Status
defines three possible values (Active
,Inactive
, andPending
). - These values can be used as
Status::Active
,Status::Inactive
, etc.
Backed Enums (Scalar Enums)
Enums can also have scalar values (int or string), known as backed enums. This allows enums to be mapped to a specific value.
Backed Enum Example (String)
php<?php
enum UserRole: string {
case Admin = 'admin';
case User = 'user';
case Guest = 'guest';
}
// Usage
$role = UserRole::Admin;
echo $role->value; // Outputs: admin
Backed Enum Example (Int)
php<?php
enum OrderStatus: int {
case Pending = 0;
case Shipped = 1;
case Delivered = 2;
}
// Usage
$status = OrderStatus::Shipped;
echo $status->value; // Outputs: 1
In these examples, enums are "backed" by specific scalar values (string
or int
), and
the scalar value is accessible through the ->value
property.
Methods in Enums
Enums can have methods, just like classes.
php<?php
enum PaymentStatus: string {
case Pending = 'pending';
case Completed = 'completed';
case Failed = 'failed';
// Method inside enum
public function label(): string {
return match($this) {
self::Pending => 'Payment is pending',
self::Completed => 'Payment completed successfully',
self::Failed => 'Payment failed',
};
}
}
// Usage
$status = PaymentStatus::Completed;
echo $status->label(); // Outputs: Payment completed successfully
Static Methods in Enums
You can also define static methods to perform operations on enums.
php<?php
enum DaysOfWeek: string {
case Monday = 'Mon';
case Tuesday = 'Tue';
case Wednesday = 'Wed';
public static function fromString(string $day): ?self {
return self::tryFrom($day) ?? null;
}
}
// Usage
$day = DaysOfWeek::fromString('Mon');
echo $day->name; // Outputs: Monday
Advantages of Using Enums
- Type Safety: Enums restrict values to a specific set, reducing the chance of errors.
- Improved Readability: Named constants are more descriptive than arbitrary integers or strings.
- Code Organization: Enum members can have associated methods, providing a clean and structured way to encapsulate logic.
Enums are a powerful addition to PHP and are particularly useful in cases where you have a fixed set of related constants (e.g., status codes, days of the week, roles). Let me know if you'd like more specific examples!