Backed enums associate enum cases with distinct string or integer values and support from() and tryFrom().
The examples below begin with the core behavior, then move to an application-oriented use.
How PHP Enums with Backed Values Works
Backed enums associate enum cases with distinct string or integer values and support from() and tryFrom().
Example 1: Basic Usage
This example uses a small input to make the main behavior visible.
<?php
enum PaymentMethod: string { case Card = "card"; case Bank = "bank"; }
echo PaymentMethod::Card->value;
Output:
card
Backed enums associate enum cases with distinct string or integer values and support from() and tryFrom().
Example 2: A Different Input
A different set of values shows the same operation in another situation.
<?php
enum Severity: int { case Low = 1; case High = 3; }
echo Severity::from(3)->name;
Output:
High
from() throws ValueError for an unknown value; tryFrom() returns null instead.
Practical Example: Applying the Feature
This example shows an application-style use of the feature, with its surrounding setup visible.
<?php
enum ExportFormat: string { case Csv = "csv"; case Json = "json"; }
$format = ExportFormat::tryFrom("csv");
echo $format?->value ?? "unsupported";
Output:
csv
The code is shown for learning. Adjust the class names, inputs and error handling to suit your application.
Important Behavior and Edge Cases
- from() throws ValueError for an unknown value; tryFrom() returns null instead.
- Backed enums associate enum cases with distinct string or integer values and support from() and tryFrom().
- Observe differences in empty inputs, invalid states and optional extension availability where relevant.
Comparison With Related Approaches
| Approach | Important Difference |
|---|---|
PHP Enums with Backed Values | Backed enums associate enum cases with distinct string or integer values and support from() and tryFrom(). |
| Alternative approach | Pure enums provide named cases without directly persisted scalar values. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
Ignoring the documented state or precondition of PHP Enums with Backed Values | from() throws ValueError for an unknown value; tryFrom() returns null instead. |
| Expecting a different type of result | Read the declared return type and distinguish returned values from changes to the source object. |
| Assuming a related API works identically | Pure enums provide named cases without directly persisted scalar values. |
Key Takeaways
- Backed enums associate enum cases with distinct string or integer values and support from() and tryFrom().
- from() throws ValueError for an unknown value; tryFrom() returns null instead.
- Use the example that matches the values, runtime version and dependencies in your application.
PHP Enums with Backed Values is useful when its behavior matches the data structure and lifecycle of your PHP application. Choose it with a clear understanding of its preconditions and returned values.