Concept Flow - Enum backed values
Define Enum with backed values
Create Enum instance
Access backed value
Use value in code
This flow shows how to define an enum with values, create an instance, and access its backed value.
<?php
enum Status: string {
case Pending = 'pending';
case Approved = 'approved';
case Rejected = 'rejected';
}
echo Status::Approved->value;
?>| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define enum Status with cases and backed string values | N/A | Enum Status created with cases Pending, Approved, Rejected |
| 2 | Access Status::Approved | Status::Approved | Enum case Approved selected |
| 3 | Get value of Status::Approved | Status::Approved->value | 'approved' |
| 4 | Print value | echo Status::Approved->value | Output: approved |
| 5 | End of script | N/A | Script ends |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| Status::Approved | N/A | Enum case object | Enum case object with value 'approved' | Enum case object with value 'approved' |
| Output | N/A | N/A | N/A | 'approved' |
PHP Enum backed values:
- Define enum with 'enum Name: type { case A = value; }'
- Backed types: string or int
- Access value with 'EnumCase->value'
- Useful for fixed sets with known values
- Example: enum Status: string { case Pending = 'pending'; }What is the main purpose of using backed enums in PHP?
Which of the following is the correct syntax to declare a backed enum with string values in PHP?
enum Status: string {
case ACTIVE = 'active';
case INACTIVE = 'inactive';
}: string.case keyword and assign a value with =.What will be the output of the following PHP code?
enum Color: int {
case RED = 1;
case GREEN = 2;
case BLUE = 3;
}
echo Color::from(2)->name;from() method returns the enum case matching the value 2, which is GREEN.->name returns the case name as a string, here "GREEN".Identify the error in the following PHP enum backed values code:
enum Status: string {
case PENDING = 'pending';
case COMPLETED = 'completed';
}
$status = Status::from('done');from() method throws an error if the value does not match any enum case.Given the following enum, which code snippet correctly converts a string value to an enum case safely without throwing an error?
enum Direction: string {
case NORTH = 'north';
case SOUTH = 'south';
case EAST = 'east';
case WEST = 'west';
}Choose the correct usage:
from() throws error if value not found; tryFrom() returns null instead.tryFrom('east') matches a valid case and safely returns the enum case.Pass the test and this pattern moves unknown