Intermediate LevelPHP 8+
How do you use PHP 8.1+ Enums and Backed Enums with custom methods and interfaces?
❓ Interview Prompt: Explain Pure Enums vs Backed Enums (string/int), Enum methods, from() / tryFrom() parsing, and JsonSerializable implementation.
PHP 8.1 introduced native Enums as first-class object singletons to replace string constant anti-patterns.
Enum Types:
1
Pure Enums: Simple named singleton cases ('enum Status { case Pending; case Active; }').
2
Backed Enums: Cases backed by scalar values ('enum Status: string { case Pending = "P"; case Active = "A"; }').
•
'Status::from("A")': Parses scalar value, returning Enum instance (throws 'ValueError' if invalid).
•
'Status::tryFrom("X")': Returns 'null' if scalar value does not match any case.
3
Enum Methods: Enums can contain methods, static methods, and implement interfaces!
Code Implementation Example
php
<?php
enum OrderStatus: string implements JsonSerializable {
case PENDING = 'pending';
case SHIPPED = 'shipped';
case CANCELLED = 'cancelled';
public function getLabel(): string {
return match($this) {
self::PENDING => 'Order Pending Payment',
self::SHIPPED => 'Package Shipped',
self::CANCELLED => 'Order Cancelled'
};
}
public function jsonSerialize(): string {
return $this->value;
}
}
$status = OrderStatus::from('shipped');
echo $status->getLabel(); // Outputs: Package Shipped💡PHP 8.1 Backed Enum with custom methods and JsonSerializable interface implementation.
🎯 Interview Key Takeaway
PHP 8.1 Enums replace string constants with type-safe Backed Enums supporting methods, interfaces, and scalar parsing.
#Enums#Backed Enums#PHP 8.1#Intermediate
Back to all PHP 8+ Questions→