PHP Velho Oeste 2024

BackedEnum インターフェイス

(PHP 8 >= 8.1.0)

はじめに

BackedEnum インターフェイスは、 Backed Enum を定義すると、PHP のエンジンが自動的に適用します。 ユーザー定義のクラスとして実装してはいけません。 列挙型はメソッドのオーバーライドを禁止しています。 デフォルトの実装は PHP のエンジンから提供されるからです。 このインターフェイスは、型チェックのためだけに存在しています。

インターフェイス概要

interface BackedEnum extends UnitEnum {
/* メソッド */
public static from(int|string $value): static
public static tryFrom(int|string $value): ?static
/* 継承したメソッド */
public static UnitEnum::cases(): array
}

目次

add a note add a note

User Contributed Notes 1 note

up
1
whatuwant
2 years ago
As of PHP 8.1, while `UnitEnum` & `BackedEnum` cannot be implemented by user-defined classes, it seems they can be extended by user-defined interfaces and eventually be implemented by enums.

<?php

interface TestEnumInterface extends \BackedEnum
{
    public function
foo(): string;
}

enum TestEnum: string implements TestEnumInterface
{
    case
CASE_1 = 'case 1';
    case
CASE_2 = 'case 2';

    public function
foo(): string
   
{
        return
'bar';
    }
}

?>
To Top