Backed enums in PHP
An enum whose cases carry string values — and behavior of their own.
<?php
enum Status: string {
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function isLive(): bool {
return $this === self::Published;
}
}
$post = Status::from('published');
echo $post->name, " -> ", $post->value, "\n";
var_dump($post->isLive());
// tryFrom returns null for unknown values instead of throwing
echo Status::tryFrom('deleted')?->value ?? 'unknown', "\n";
How it works
enum Status: stringbinds each case to a database-friendly value.- Methods on the enum let a case answer questions like
isLive. fromthrows on unknown input;tryFromreturns null instead.
Keywords and builtins used here
caseechofunctionisLivepublicreturnvar_dump
The run, in numbers
- Lines
- 17
- Characters to type
- 412
- Tokens
- 87
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 65 seconds.
Step 3 of 3 in Null & errors, step 21 of 27 in Language basics.