PHP Enum Pro Tip: How to Statically Get a Label from a Value
Content
## Problem Background
When developing multi-language applications, a common task is to fetch a text label from a PHP Enum based on its backing value (e.g., an ID). A frequent requirement is to implement a static method that allows us to call it directly via the class name and a value, without first instantiating the enum. For instance, we want to achieve a call like this:
```php
// Goal: Get the English label 'Article' for the value 11
$en_label = ContentType::getEnglishLabel(11);
```
Let's assume we have the following `ContentType` enum that supports both Chinese and English labels.
```php
<?php
namespace App\Constants\Lib00;
enum ContentType: int
{
case ANNOUNCEMENT = 1; // Website Announcement
case ARTICLE = 11; // General Article
case VIDEO = 21; // Video
public function label(): string
{
return match($this) {
self::ANNOUNCEMENT => '网站公告',
self::ARTICLE => '一般文章',
self::VIDEO => '视频',
};
}
public function englishLabel(): string
{
return match($this) {
self::ANNOUNCEMENT => 'Announcement',
self::ARTICLE => 'Article',
self::VIDEO => 'Video',
};
}
// ... other instance methods
}
```
---
## The Solution: Combining `tryFrom()` and the Nullsafe Operator
To achieve a static call like `ContentType::getEnglishLabel(11)`, the most elegant and efficient approach is to combine the `tryFrom()` method provided by PHP 8.1+ enums with the nullsafe operator `?->`. You just need to add the following static method to your enum.
```php
/**
* Get the English label for a given enum value.
* @param int $value The enum case value
* @return string|null Returns null if the value is not found
*/
public static function getEnglishLabel(int $value): ?string
{
return self::tryFrom($value)?->englishLabel();
}
```
---
## How It Works
This single, concise line of code comprises three key parts:
1. `public static function getEnglishLabel(...)`: Defines a public static method. The `static` keyword means you can call it directly on the class `ContentType::` without needing to create an enum instance first.
2. `self::tryFrom($value)`: This is a built-in enum method that attempts to find a corresponding enum case (`ContentType::ARTICLE`) from the provided value (e.g., `11`). Unlike the `from()` method, `tryFrom()` safely returns `null` if no match is found, instead of throwing a fatal error, making our code more robust.
3. `?->englishLabel()`: This is the **Nullsafe Operator**. It works as follows:
* If the expression on the left (`self::tryFrom($value)`) returns a valid enum instance, it proceeds to call the `englishLabel()` method on that instance.
* If the expression on the left returns `null`, the entire chain of execution stops immediately and returns `null`, perfectly avoiding the common "Attempt to call method on null" error.
---
## Complete Code and Usage Example
After adding the new static method, your complete enum code, as provided by DP@lib00, will look like this:
```php
<?php
namespace App\Constants\WikiLib00Com;
enum ContentType: int
{
case ANNOUNCEMENT = 1;
case ARTICLE = 11;
case VIDEO = 21;
public function label(): string
{
return match($this) {
self::ANNOUNCEMENT => '网站公告',
self::ARTICLE => '一般文章',
self::VIDEO => '视频',
};
}
public function englishLabel(): string
{
return match($this) {
self::ANNOUNCEMENT => 'Announcement',
self::ARTICLE => 'Article',
self::VIDEO => 'Video',
};
}
/**
* Get the English label for a given enum value.
* @param int $value The enum case value
* @return string|null Returns null if the value is not found
*/
public static function getEnglishLabel(int $value): ?string
{
return self::tryFrom($value)?->englishLabel();
}
}
```
Now, you can make your calls safely:
```php
// Successfully find a match
$en_label = ContentType::getEnglishLabel(11);
var_dump($en_label); // Outputs: string(7) "Article"
// Pass a value that does not exist
$not_found_label = ContentType::getEnglishLabel(99);
var_dump($not_found_label); // Outputs: NULL
```
This approach is not only concise and readable but also very safe, making it a best practice for handling this kind of requirement.
Related Contents
PHP Log Aggregation Performance Tuning: Database vs. Application Layer - The Ultimate Showdown for Millions of Records
Duration: 00:00 | DP | 2026-01-06 08:05:09MySQL TIMESTAMP vs. DATETIME: The Ultimate Showdown on Time Zones, UTC, and Storage
Duration: 00:00 | DP | 2025-12-02 08:31:40The Ultimate 'Connection Refused' Guide: A PHP PDO & Docker Debugging Saga of a Forgotten Port
Duration: 00:00 | DP | 2025-12-03 09:03:20The Ultimate PHP Guide: How to Correctly Handle and Store Markdown Line Breaks from a Textarea
Duration: 00:00 | DP | 2025-11-20 08:08:00Stop Mixing Code and User Uploads! The Ultimate Guide to a Secure and Scalable PHP MVC Project Structure
Duration: 00:00 | DP | 2026-01-13 08:14:11Mastering PHP: How to Elegantly Filter an Array by Keys Using Values from Another Array
Duration: 00:00 | DP | 2026-01-14 08:15:29Stop Manual Debugging: A Practical Guide to Automated Testing in PHP MVC & CRUD Applications
Duration: 00:00 | DP | 2025-11-16 16:32:33Mastering PHP Switch: How to Handle Multiple Conditions for a Single Case
Duration: 00:00 | DP | 2025-11-17 09:35:40`self::` vs. `static::` in PHP: A Deep Dive into Late Static Binding
Duration: 00:00 | DP | 2025-11-18 02:38:48PHP String Magic: Why `{static::$table}` Fails and 3 Ways to Fix It (Plus Security Tips)
Duration: 00:00 | DP | 2025-11-18 11:10:21Can SHA256 Be "Decrypted"? A Deep Dive into Hash Function Determinism and One-Way Properties
Duration: 00:00 | DP | 2025-11-19 04:13:29The Magic of PHP Enums: Elegantly Convert an Enum to a Key-Value Array with One Line of Code
Duration: 00:00 | DP | 2025-12-16 03:39:10One-Click Code Cleanup: The Ultimate Guide to PhpStorm's Reformat Code Shortcut
Duration: 00:00 | DP | 2026-02-03 09:34:00Upgrading to PHP 8.4? How to Fix the `session.sid_length` Deprecation Warning
Duration: 00:00 | DP | 2025-11-20 22:51:17Streamline Your Yii2 Console: How to Hide Core Commands and Display Only Your Own
Duration: 00:00 | DP | 2025-12-17 16:26:40From Guzzle to Native cURL: A Masterclass in Refactoring a PHP Translator Component
Duration: 00:00 | DP | 2025-11-21 07:22:51Why Are My Mac Files Duplicated on NFS Shares? The Mystery of '._' Files Solved with PHP
Duration: 00:00 | DP | 2025-12-18 16:58:20Markdown Header Not Rendering? The Missing Newline Mystery Solved
Duration: 00:00 | DP | 2025-11-23 02:00:39Recommended
`self::` vs. `static::` in PHP: A Deep Dive into Late Static Binding
00:00 | 37Explore the crucial difference between PHP's `self...
The Ultimate Guide to CSS Colors: From RGBA to HSL for Beginners
00:00 | 25Confused by CSS color values like `rgba(8, 219, 21...
The Art of URL Naming: Hyphen (-) vs. Underscore (_), Which is the SEO and Standard-Compliant Champion?
00:00 | 3Choosing between hyphens (-) and underscores (_) i...
PHP Dependency Injection in Practice: Resolving the 'Too Few Arguments' Fatal Error in Controllers
00:00 | 1Injecting the Request object via the constructor i...