Enums provide native named cases instead of strings that can contain invalid or misspelled states.
The examples below begin with the core behavior, then move to an application-oriented use.
How PHP Enumerations Works
Enums provide native named cases instead of strings that can contain invalid or misspelled states.
Example 1: Basic Usage
This example uses a small input to make the main behavior visible.
<?php
enum TrafficLight { case Red; case Yellow; case Green; }
echo TrafficLight::Red->name;
Output:
Red
Enums provide native named cases instead of strings that can contain invalid or misspelled states.
Example 2: A Different Input
A different set of values shows the same operation in another situation.
<?php
enum TemperatureState { case Cold; case Warm; case Hot; }
var_dump(TemperatureState::Warm === TemperatureState::Hot);
Output:
bool(false)
Enum cases are objects; use ->name for their names rather than treating them as plain strings.
Practical Example: Applying the Feature
This example shows an application-style use of the feature, with its surrounding setup visible.
<?php
enum Priority { case Low; case Normal; case High; }
$priority = Priority::High;
echo $priority->name;
Output:
High
The code is shown for learning. Adjust the class names, inputs and error handling to suit your application.
Important Behavior and Edge Cases
- Enum cases are objects; use ->name for their names rather than treating them as plain strings.
- Enums provide native named cases instead of strings that can contain invalid or misspelled states.
- Observe differences in empty inputs, invalid states and optional extension availability where relevant.
Comparison With Related Approaches
| Approach | Important Difference |
|---|---|
PHP Enumerations | Enums provide native named cases instead of strings that can contain invalid or misspelled states. |
| Alternative approach | Backed enums attach a string or integer value suitable for persistence or APIs. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
Ignoring the documented state or precondition of PHP Enumerations | Enum cases are objects; use ->name for their names rather than treating them as plain strings. |
| 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 | Backed enums attach a string or integer value suitable for persistence or APIs. |
Key Takeaways
- Enums provide native named cases instead of strings that can contain invalid or misspelled states.
- Enum cases are objects; use ->name for their names rather than treating them as plain strings.
- Use the example that matches the values, runtime version and dependencies in your application.
PHP Enumerations 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.