PHP 8.1 で入った enum(列挙型)のうち、ケースに文字列か整数の値を持たせる「Backed enum」の使い方をまとめます。値から enum に変える from() と tryFrom() の違い、型が違う値を渡したときに何が起きるか(strict_types のあり・なし)、フォームやクエリ文字列の値を enum にする書き方、つまずきやすい点(配列のキーにできない、文字列と == で比べても一致しない)を、DockerのPHPで実際に動かして確かめました。
この記事は、MacとWindowsの両方の読者を対象にしています。PHPはDockerのコンテナの中で動かすので、OSで変わるのは、変数の書き方と、フォルダをコンテナに渡す docker run の書き方くらいです。コマンドは Claude(AI)が実行して確認しました。本文の出力は、Windows 11 のGit Bashから上から順に実行した結果です。PowerShellで実行した結果は、最後の章に載せました。Macでは確認していません。
結論
from() と tryFrom() は、渡した値によって次のように動きました(PHP 8.5.13 と 8.6.0 で同じ結果)。
| 渡した値 | from() | tryFrom() |
|---|---|---|
| どれかのケースの値と一致する | そのケース | そのケース |
受け付けられる型だが(strict_types がないときは型を変換したうえで)、どのケースの値とも一致しない | ValueError | null |
受け付けられない型(整数のenumに 'abc'、配列など) | TypeError | TypeError |
tryFrom()は「例外を投げないfrom()」ではありません。nullを返すのは、受け付けられる型の値で(strict_typesがないときは型を変換したうえで)ケースが見つからないときだけです。受け付けられない型の値は、tryFrom()でもTypeErrorになります。どの型が受け付けられるかは、strict_typesのあり・なしで変わります(下の章の表)。declare(strict_types=1);のファイルでは、整数のenumに文字列の'3'を渡してもTypeErrorです。フォームやクエリ文字列の値(文字列)は、filter_var($raw, FILTER_VALIDATE_INT)などで整数にしてからtryFrom()に渡します。strict_typesがないファイルでは、型が変換されます。整数のenumに'2'を渡すと通り、2.5も(非推奨の警告つきで)2のケースに、trueも1のケースになりました。気づかないまま通ってしまうので、入力を enum にするコードはstrict_typesを付け、変換を自分で書くほうが安全です。- ケースの値は大文字・小文字を区別します。ケースの名前(
Published)ではなく値(published)を渡します。 - enum のケースは、配列のキーにできません(
TypeError)。キーには->valueを使います。
環境
- PHP 8.5.13(Docker Hubの公式イメージ
php:8.5.13-cli。digestで固定) - 同じファイルを PHP 8.6.0(
php:8.6.0-cli)でも実行し、出力が版の表示以外は同じであることを確かめた - Docker 29.9.3(Docker Desktop、Linuxコンテナ)、Windows 11 のGit Bash、PowerShell 7.6.10
- PHPの設定は公式イメージの既定のまま(php.ini なし)。
error_reportingは未設定で PHP 8 の既定のE_ALL、display_errorsはSTDOUTでした(php -iで確認)。本文の出力に出てくるDeprecated:の警告は、この設定で画面に出たものです。設定によっては表示されません - 確認日: 2026-11-25
準備:フォルダとイメージ
作業用のフォルダを作り、その中で作業します。使うイメージは、版がずれないように digest まで書いて変数 IMG に入れておきます。WindowsのGit Bashでは、先に export MSYS_NO_PATHCONV=1 を実行してください。Git Bashは /work のような引数をWindowsのパスに変換することがあり、Dockerの公式ドキュメントでもこの設定が案内されています。
Macのターミナル(zsh、bash)とWindowsのGit Bashでは、次のように書きます。
mkdir php-enum-demo
cd php-enum-demo
IMG="php:8.5.13-cli@sha256:dbf32b33595283b79fd1a37ebc1614bdf1b83d3750daad9a57d67dbb9b96ec16"
WindowsのPowerShellでは、変数の書き方が変わります。
mkdir php-enum-demo
cd php-enum-demo
$IMG = "php:8.5.13-cli@sha256:dbf32b33595283b79fd1a37ebc1614bdf1b83d3750daad9a57d67dbb9b96ec16"
PHPのファイルは、このフォルダをコンテナの /work に渡して実行します。
docker run --rm -v "$PWD:/work" -w /work "$IMG" php ファイル名.php
PowerShellでは $PWD を ${PWD} にします(docker run --rm -v "${PWD}:/work" -w /work $IMG php ファイル名.php)。
enumを作る
記事の状態を表す文字列のenum Status と、優先度を表す整数のenum Priority を作ります。Status.php には、表示名を返すメソッド、定数、インターフェースも入れました。
Status.php
<?php
interface HasLabel
{
public function label(): string;
}
enum Status: string implements HasLabel
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public const DEFAULT = self::Draft;
public function label(): string
{
return match ($this) {
self::Draft => '下書き',
self::Published => '公開中',
self::Archived => 'アーカイブ',
};
}
public function isVisible(): bool
{
return $this === self::Published;
}
/** @return array<string, string> 値 => 表示名 */
public static function options(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->label();
}
return $options;
}
}
Priority.php
<?php
enum Priority: int
{
case Low = 1;
case Medium = 2;
case High = 3;
}
enum Status: stringのように、名前の後にstringかintを書くと Backed enum になります。全部のケースに、重ならない値を書く必要があります。int|stringのように両方は選べません(PHPマニュアル)。- enum にはメソッド、静的メソッド、定数を書け、インターフェースを実装できます。プロパティ(状態)、コンストラクタ、継承は使えません(PHPマニュアル)。
- Backed enum でない、値を持たない enum(
enum Suit { case Hearts; })には、この記事のfrom()とtryFrom()がありません。
基本の使い方
basics.php
<?php
require __DIR__ . '/Status.php';
$status = Status::Published;
var_dump($status);
echo $status->name, PHP_EOL;
echo $status->value, PHP_EOL;
echo $status->label(), PHP_EOL;
var_dump($status->isVisible());
var_dump($status instanceof HasLabel);
var_dump(Status::DEFAULT);
foreach (Status::cases() as $case) {
echo $case->name, ' = ', $case->value, PHP_EOL;
}
print_r(Status::options());
echo json_encode(['id' => 1, 'status' => $status]), PHP_EOL;
var_dump($status === Status::from('published'));
var_dump($status == 'published');
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php basics.php
enum(Status::Published)
Published
published
公開中
bool(true)
bool(true)
enum(Status::Draft)
Draft = draft
Published = published
Archived = archived
Array
(
[draft] => 下書き
[published] => 公開中
[archived] => アーカイブ
)
{"id":1,"status":"published"}
bool(true)
bool(false)
->nameはケースの名前、->valueは値です。Status::cases()は、全部のケースを、書いた順に返します。セレクトボックスの選択肢を作るときに使えます(options())。json_encode()では、Backed enum は値("published")になります。- ケースは1つずつしかないオブジェクトなので、
===で比べられます。from('published')で作ったものも、Status::Publishedと===で一致しました。 - 文字列とは、
==で比べても一致しません(最後のbool(false))。値と比べるなら$status->value === 'published'と書くか、先に enum に変えてから比べます。
fromとtryFromの違い
以降の例では、1つの式を実行して、結果か例外を1行で表示する関数 show() を使います。例外が出ても、次の例が実行されるようにするためです。
show.php
<?php
// 1つの式を実行し、結果か、投げられた例外を1行で表示する。
// 例外が出ても、次の例は実行される。
function show(string $code, callable $fn): void
{
try {
$result = $fn();
echo $code, ' => ', var_export($result, true), PHP_EOL;
} catch (Throwable $e) {
echo $code, ' => ', $e::class, ': ', $e->getMessage(), PHP_EOL;
}
}
from.php
<?php
require __DIR__ . '/Status.php';
require __DIR__ . '/show.php';
show("Status::from('published')", fn () => Status::from('published'));
show("Status::from('Published')", fn () => Status::from('Published'));
show("Status::tryFrom('Published')", fn () => Status::tryFrom('Published'));
show("Status::tryFrom('unknown') ?? Status::DEFAULT", fn () => Status::tryFrom('unknown') ?? Status::DEFAULT);
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php from.php
Status::from('published') => \Status::Published
Status::from('Published') => ValueError: "Published" is not a valid backing value for enum Status
Status::tryFrom('Published') => NULL
Status::tryFrom('unknown') ?? Status::DEFAULT => \Status::Draft
from()は、どのケースにも当たらないとValueErrorを投げます。tryFrom()はnullを返すので、??で初期値にできます。'Published'(ケースの名前)は、値ではないので当たりません。
from() の例外を捕まえないと、スクリプトはそこで止まります。終了コードは 255 でした。
uncaught.php
<?php
require __DIR__ . '/Status.php';
$status = Status::from('unknown');
echo 'ここは実行されない', PHP_EOL;
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php uncaught.php
Fatal error: Uncaught ValueError: "unknown" is not a valid backing value for enum Status in /work/uncaught.php:4
Stack trace:
#0 /work/uncaught.php(4): Status::from('unknown')
#1 {main}
thrown in /work/uncaught.php on line 4
$ echo $?
255
PowerShellでは、終了コードは $? ではなく $LASTEXITCODE で確かめます(PowerShellの $? は、直前のコマンドが成功したかを真偽値で表します)。PowerShellで実行した確認でも、$LASTEXITCODE は 255 でした。
PHPマニュアルでは、from() は値が信頼できて、見つからないことがアプリケーションを止めるべき誤りのとき、tryFrom() は値が信頼できず、呼び出し側でエラー処理や初期値を決めたいときに向く、と説明されています。データベースに保存した値を読むときは from()、利用者が送ってきた値は tryFrom()、と使い分けるのが分かりやすいです。
型が違う値を渡したとき(strict_typesのあり・なし)
from() と tryFrom() の引数の型は int|string です。型が違う値を渡したときの動きは、呼び出す側のファイルに declare(strict_types=1); があるかで変わります。まず、ないファイルです。
types.php
<?php
require __DIR__ . '/Status.php';
require __DIR__ . '/Priority.php';
require __DIR__ . '/show.php';
show("Priority::from(2)", fn () => Priority::from(2));
show("Priority::from('2')", fn () => Priority::from('2'));
show("Priority::from(2.5)", fn () => Priority::from(2.5));
show("Priority::from(true)", fn () => Priority::from(true));
show("Priority::from('abc')", fn () => Priority::from('abc'));
show("Priority::tryFrom('abc')", fn () => Priority::tryFrom('abc'));
show("Priority::tryFrom(9)", fn () => Priority::tryFrom(9));
show("Status::from(1)", fn () => Status::from(1));
show("Status::tryFrom(1)", fn () => Status::tryFrom(1));
show("Status::tryFrom(null)", fn () => Status::tryFrom(null));
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php types.php
Priority::from(2) => \Priority::Medium
Priority::from('2') => \Priority::Medium
Deprecated: Implicit conversion from float 2.5 to int loses precision in /work/types.php on line 8
Priority::from(2.5) => \Priority::Medium
Priority::from(true) => \Priority::Low
Priority::from('abc') => TypeError: Priority::from(): Argument #1 ($value) must be of type int, string given
Priority::tryFrom('abc') => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
Priority::tryFrom(9) => NULL
Status::from(1) => ValueError: "1" is not a valid backing value for enum Status
Status::tryFrom(1) => NULL
Deprecated: Status::tryFrom(): Passing null to parameter #1 ($value) of type string|int is deprecated in /work/types.php on line 15
Status::tryFrom(null) => NULL
strict_types を付けた版 types-strict.php は、types.php をコピーして、1行目の <?php の次の行に declare(strict_types=1); を足しただけのファイルです。エディタで作ってください。先頭はこうなります(3行目から後は、types.php の2行目から後と同じ)。
<?php
declare(strict_types=1);
require __DIR__ . '/Status.php';
(省略)
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php types-strict.php
Priority::from(2) => \Priority::Medium
Priority::from('2') => TypeError: Priority::from(): Argument #1 ($value) must be of type int, string given
Priority::from(2.5) => TypeError: Priority::from(): Argument #1 ($value) must be of type int, float given
Priority::from(true) => TypeError: Priority::from(): Argument #1 ($value) must be of type int, true given
Priority::from('abc') => TypeError: Priority::from(): Argument #1 ($value) must be of type int, string given
Priority::tryFrom('abc') => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
Priority::tryFrom(9) => NULL
Status::from(1) => TypeError: Status::from(): Argument #1 ($value) must be of type string, int given
Status::tryFrom(1) => TypeError: Status::tryFrom(): Argument #1 ($value) must be of type string, int given
Status::tryFrom(null) => TypeError: Status::tryFrom(): Argument #1 ($value) must be of type string, null given
2つの結果を並べるとこうなります。
| 式 | strict_typesなし | strict_typesあり |
|---|---|---|
Priority::from('2') | Priority::Medium | TypeError |
Priority::from(2.5) | Priority::Medium(非推奨の警告) | TypeError |
Priority::from(true) | Priority::Low | TypeError |
Priority::from('abc') | TypeError | TypeError |
Priority::tryFrom('abc') | TypeError | TypeError |
Status::from(1) | ValueError("1" として探す) | TypeError |
Status::tryFrom(1) | null | TypeError |
Status::tryFrom(null) | null(非推奨の警告) | TypeError |
- PHPマニュアルでは、
from()とtryFrom()は通常の型の規則に従い、strict_typesがないときは整数・文字列・浮動小数点数が変換され、あるときは文字列のenumに整数を渡す(またはその逆)とTypeError、浮動小数点数はいつでもTypeError、と説明されています。結果はその説明どおりでした。 strict_typesは、関数を「呼び出す側」のファイルで決まります(PHPマニュアル)。enum を定義したファイルに付けても、呼び出す側のファイルに付いていなければ、変換されます。2.5の非推奨の警告は、PHP 8.1 で非推奨になった「精度が落ちる浮動小数点数から整数への暗黙の変換」です。nullの警告は、同じく PHP 8.1 で非推奨になった「組み込みの関数の、nullを許さない引数にnullを渡すこと」です。どちらも PHP 8.1 の移行ガイドに載っています。Status::from(1)は、strict_typesがないと整数1が文字列"1"に変換され、その値のケースがないのでValueErrorになりました。
フォームやクエリ文字列の値をenumにする
フォームやクエリ文字列から来る値は、文字列です。項目がなければ null、?p[]=3 のように送られると配列のこともあります。strict_types を付けたファイルで、そのまま tryFrom() に渡した場合と、先に型を確かめてから渡した場合を比べます。
input.php
<?php
declare(strict_types=1);
require __DIR__ . '/Status.php';
require __DIR__ . '/Priority.php';
require __DIR__ . '/show.php';
// フォームやクエリ文字列から来た値(文字列か null、配列のこともある)を enum にする。
// 読めないものと、どのケースにも当たらないものは null にする。
function parsePriority(mixed $raw): ?Priority
{
$int = filter_var($raw, FILTER_VALIDATE_INT);
if ($int === false) {
return null;
}
return Priority::tryFrom($int);
}
function parseStatus(mixed $raw): ?Status
{
return is_string($raw) ? Status::tryFrom($raw) : null;
}
foreach (['3', '9', 'abc', '2.5', '', null, ['3']] as $raw) {
$label = json_encode($raw);
show("Priority::tryFrom($label)", fn () => Priority::tryFrom($raw));
show("parsePriority($label)", fn () => parsePriority($raw));
}
foreach (['draft', 'Draft', null, ['draft']] as $raw) {
$label = json_encode($raw);
show("Status::tryFrom($label)", fn () => Status::tryFrom($raw));
show("parseStatus($label)", fn () => parseStatus($raw));
}
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php input.php
Priority::tryFrom("3") => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
parsePriority("3") => \Priority::High
Priority::tryFrom("9") => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
parsePriority("9") => NULL
Priority::tryFrom("abc") => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
parsePriority("abc") => NULL
Priority::tryFrom("2.5") => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
parsePriority("2.5") => NULL
Priority::tryFrom("") => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, string given
parsePriority("") => NULL
Priority::tryFrom(null) => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, null given
parsePriority(null) => NULL
Priority::tryFrom(["3"]) => TypeError: Priority::tryFrom(): Argument #1 ($value) must be of type int, array given
parsePriority(["3"]) => NULL
Status::tryFrom("draft") => \Status::Draft
parseStatus("draft") => \Status::Draft
Status::tryFrom("Draft") => NULL
parseStatus("Draft") => NULL
Status::tryFrom(null) => TypeError: Status::tryFrom(): Argument #1 ($value) must be of type string, null given
parseStatus(null) => NULL
Status::tryFrom(["draft"]) => TypeError: Status::tryFrom(): Argument #1 ($value) must be of type string, array given
parseStatus(["draft"]) => NULL
- 整数のenumに文字列をそのまま渡すと、
'3'のように正しい値でもTypeErrorになりました。filter_var($raw, FILTER_VALIDATE_INT)で整数にしてから渡すと、'3'はケースになり、'abc'、'2.5'、空文字、null、配列はnullになりました。FILTER_VALIDATE_INTは、整数として読めればintに変換し、読めなければfalseを返します(文字列は前後の空白を取り除いてから確かめます。PHPマニュアル)。 - 文字列のenumは、文字列ならそのまま
tryFrom()に渡せます。nullや配列はTypeErrorになるので、is_string()で確かめてから渡しました。 parsePriority()がnullを返したときに、エラーにするか初期値を使うかは、呼び出す側で決めます。
enumを配列のキーにしたいとき
ケースごとに数を数えるときなど、enum をそのまま配列のキーにしたくなりますが、できません。
keys.php
<?php
require __DIR__ . '/Status.php';
require __DIR__ . '/show.php';
show('[Status::Draft => 1]', fn () => [Status::Draft => 1]);
// 配列のキーには ->value を使う
$counts = [];
foreach ([Status::Draft, Status::Published, Status::Draft] as $status) {
$counts[$status->value] = ($counts[$status->value] ?? 0) + 1;
}
print_r($counts);
$ docker run --rm -v "$PWD:/work" -w /work "$IMG" php keys.php
[Status::Draft => 1] => TypeError: Cannot access offset of type Status on array
Array
(
[draft] => 2
[published] => 1
)
配列のキーには ->value を使います。キーから enum に戻すときは Status::from($key) です(->name をキーにした場合は、from() では戻せません。from() が探すのは値です)。
Laravelで使う場合
Laravel では、Eloquent のモデルの属性を enum に変換するキャスト(casts() で属性に enum のクラスを指定する)と、リクエストの値が enum のどれかの値かを確かめるバリデーションのルール(Rule::enum())が用意されています(Laravel 13.x の公式ドキュメント)。この記事では、Laravel での動作は確かめていません。
WindowsのPowerShellで実行する場合
Windows 11 のPowerShell 7.6.10 から、basics.php、from.php、uncaught.php、input.php を実行しました。ファイルの改行はCRLF(Windowsのエディタで保存したとき)にして試しています。4つとも、出力は本文と同じでした(終了コードも同じ)。from.php の例です。
PS> docker run --rm -v "${PWD}:/work" -w /work $IMG php from.php
Status::from('published') => \Status::Published
Status::from('Published') => ValueError: "Published" is not a valid backing value for enum Status
Status::tryFrom('Published') => NULL
Status::tryFrom('unknown') ?? Status::DEFAULT => \Status::Draft
ただし、PowerShellが docker の出力を文字列として受け取ったとき(変数に入れる、パイプで次のコマンドに渡すなど)は、日本語が化けました。今回の確認では、[Console]::OutputEncoding の既定が Shift_JIS で、UTF-8 で出力されたPHPの日本語(basics.php の 公開中 など)が化けて記録されました。次の1行で UTF-8 にすると、本文と同じ日本語になりました。ターミナルの画面に直接表示した場合に化けるかは、確かめていません。
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Windows PowerShell 5.1 と、Macのターミナルでは確認していません。Macでも同じ docker のコマンドを使う想定です。
参考URL
- PHP: Backed enumerations – Manual
- PHP: BackedEnum::from – Manual
- PHP: BackedEnum::tryFrom – Manual
- PHP: Enumeration methods – Manual
- PHP: Value listing – Manual
- PHP: Differences from objects – Manual
- PHP: Serialization – Manual
- PHP: Type declarations – Manual(Strict typing)
- PHP: Deprecated Features(PHP 8.1) – Manual
- PHP: Validation filters – Manual(FILTER_VALIDATE_INT)
- Eloquent: Mutators & Casting(Enum Casting) – Laravel 13.x
- Validation(enum) – Laravel 13.x
- Troubleshoot topics for Docker Desktop(Git Bash と MSYS_NO_PATHCONV)
- php – Official Image | Docker Hub
- about_Automatic_Variables – PowerShell($? と $LASTEXITCODE)

コメント