0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

PHP 8.0.0から追加された match 式は、従来の ifswitch と比較し、より安全かつシンプルな条件分岐です。

「より厳密な比較をしたい」「単純な値のマッピングをしたい」といったケースで有効だと思います。

本記事では、matchの基本構文(PHPマニュアル)や、if / switch との違い、使いどころや注意点について紹介します。

※ 下記のバージョンを参考にしています。
PHP 8.0.0 以上

match 式って何?

match は「条件に応じた値を返す」比較的新しい構文で、次のように使います。

$status = 1;

$message = match ($status) {
    0    => '未処理',
    1, 2 => '処理中',
    3    => '完了',
    default => '不明',
};

上記のように、条件に合致した値をそのまま返せるのが大きな特徴です。

if / switch / match の比較

特徴 if switch match
比較方法 条件式で指定できる 緩やか(==) 厳密(===)
戻り値 なし(文) なし(文) 値を返す(式)
パターンの網羅 不要 不要 必須(マッチしないと例外)
複雑な処理 OK OK 不可(値の返却のみ)

メリット

  • 厳密な比較(===)による安全性
  • 戻り値があるため、代入がシンプル
  • 記述がシンプルで読みやすい

デメリット

  • 複雑な処理(ログ出力 や DBアクセスなど)は書けない(ifswitch が適している)
  • 全パターンを網羅しないと UnhandledMatchError(PHPマニュアル) になる
  • PHP 8.0.0 以降でしか利用できない

使いどころ

  • Enumと組み合わせてラベル変換
enum Status: int {
    case Draft     = 0;
    case Published = 1;
    case Archived  = 2;

    public function label(): string {
        return match($this) {
            self::Draft     => '下書き',
            self::Published => '公開済み',
            self::Archived  => 'アーカイブ',
        };
    }
}
  • 単純な値のマッピング
$month = 'Jun';

$monthLabel = match($month) {
    ...
    'May' => '5月',
    'Jun' => '6月',
    'Jul' => '7月',
    ...
    default => '不明',
};

echo $monthLabel; // 6月

使わない方が良いケース

複数の処理(ログ出力、DBアクセス、複雑な条件分岐など)をしたいときは ifswitch を使う方が適切

// match では書けない
if ($status === 1) {
    Log::info('ステータス1です!');
    $message = '処理中';
}

まとめ

  • match は値に応じて 戻り値を返すのに特化した構文
  • if / switch に比べて安全で読みやすいが、複雑な処理には不向き
  • Enum との相性が良く、可読性に優れる
  • 使い分けを意識すれば、コードの可読性と安全性が向上する

おまけ: switch との比較

単純な値のマッピングであれば match を使う方が型安全で読みやすい

// switch
switch ($status) {
    case 0:
        $label = '下書き';
        break;
    case 1:
        $label = '公開済み';
        break;
    default:
        $label = '不明';
}

// match
$label = match($status) {
    0 => '下書き',
    1 => '公開済み',
    default => '不明',
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?