PHP 8.1 enum with methods and match expression
PHP Dasun Kalupahana 76 views
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string
{
return match ($this) {
self::Draft => 'Work in progress',
self::Published => 'Live',
self::Archived => 'Hidden',
};
}
public static function fromLabelSafe(string $v): self
{
return self::tryFrom($v) ?? self::Draft;
}
}
echo Status::from('published')->label(), PHP_EOL; // Live
echo Status::fromLabelSafe('nope')->name, PHP_EOL; // Draft
echo implode(', ', array_column(Status::cases(), 'value')), PHP_EOL; // draft, published, archived
Backed enums can hold methods and static helpers. match gives a strict value mapping, and tryFrom with ?? provides a safe fallback. Needs PHP 8.1+.
Learn more on the blog
PHP
How to Detect and Fix PHP Memory Leaks
Last updated: 5 November 2026. See the update log at the end.In...
9 min read
Industry Trends
AI Coding Prompts That Actually Improve Productivity
Most lists of "best AI coding prompts" are collections of clever wording....
8 min read
Laravel
Laravel Herd Setup: Sites, PHP Versions, HTTPS and Databases
Laravel Herd is a local development environment for macOS and Windows that...
5 min read