Enums in PHP 8.1
Oleksandr Bondarenko
Java developer | Full Stack Developer | Spring Developer
1. Concept Overview: PHP 8.1 introduces the ability to use enums, which allows creating a set of constant values with strong typing. Let's look at examples related to order statuses.
2. Enum Declaration:
enum OrderStatus
{
case NEW;
case PROCESSING;
case SHIPPED;
case DELIVERED;
}
We've defined an enum OrderStatus with order statuses: "NEW," "PROCESSING," "SHIPPED," and "DELIVERED."
3. Usage in a Class:
class Order
{
public function __construct(public OrderStatus $status) {}
}
Now, we can use the OrderStatus enum as the type for the status property of the Order class.
4. Creating an Order:
$newOrder = new Order(OrderStatus::NEW);
This is how we create a new order with the "NEW" status.
5. Enum Methods:
领英推荐
enum OrderStatus
{
// ...
public function getStatusText(): string
{
return match($this)
{
OrderStatus::NEW => 'Order created',
OrderStatus::PROCESSING => 'Order is being processed',
OrderStatus::SHIPPED => 'Order has been shipped',
OrderStatus::DELIVERED => 'Order has been delivered',
};
}
}
We can define the getStatusText() method, which returns a textual description of the order status.
6. Enum Interfaces:
interface StatusDescription
{
public function getStatusText(): string;
}
enum OrderStatus implements StatusDescription
{
// ...
}
Enums can implement interfaces, just like regular classes.
7. Serialization and Deserialization:
$orderStatus = OrderStatus::SHIPPED;
$serializedStatus = $orderStatus->value; // "SHIPPED"
$restoredStatus = OrderStatus::from('DELIVERED'); // OrderStatus::DELIVERED
We can serialize the order status and restore it from its value.
8. Getting a List of All Statuses:
$allStatuses = OrderStatus::cases(); // [OrderStatus::NEW, OrderStatus::PROCESSING, OrderStatus::SHIPPED, OrderStatus::DELIVERED]
We can obtain a list of all possible order statuses.
9. Other: Enums are represented as singleton objects, allowing for comparisons and use in various contexts.
This is just one of the possible examples of using enums in PHP 8.1 to represent order statuses. They simplify code and make it more understandable and structured.