열거형 메서드

(PHP 8 >= 8.1.0)

열거형(순수 열거형 및 지원 열거형 모두)에는 메서드가 포함될 수 있으며 인터페이스를 구현할 수 있습니다. Enum이 인터페이스를 구현하는 경우 해당 인터페이스에 대한 모든 유형 검사는 해당 Enum의 모든 경우도 수락합니다.

                  
<?php
interface Colorful
{
    public function color(): string;
}

enum Suit implements Colorful
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;

    // Fulfills the interface contract.
    public function color(): string
    {
        return match($this) {
            Suit::Hearts, Suit::Diamonds => 'Red',
            Suit::Clubs, Suit::Spades => 'Black',
        };
    }

    // Not part of an interface; that's fine.
    public function shape(): string
    {
        return "Rectangle";
    }
}

function paint(Colorful $c) { ... }

paint(Suit::Clubs);  // Works

print Suit::Diamonds->shape(); // prints "Rectangle"
?>
                  
                

이 예에서 Suit의 네 가지 인스턴스에는 모두 color()shape()의 두 가지 메서드가 있습니다. 호출 코드 및 유형 검사에 관한 한 다른 개체 인스턴스와 정확히 동일하게 작동합니다.

Backed Enum에서 인터페이스 선언은 지원 유형 선언 뒤에 옵니다.

                  
<?php
interface Colorful
{
    public function color(): string;
}

enum Suit: string implements Colorful
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    // Fulfills the interface contract.
    public function color(): string
    {
        return match($this) {
            Suit::Hearts, Suit::Diamonds => 'Red',
            Suit::Clubs, Suit::Spades => 'Black',
        };
    }
}
?>
                  
                

메소드 내에서 $this 변수가 정의되고 Case 인스턴스를 참조합니다.

메서드는 임의로 복잡할 수 있지만 실제로는 일반적으로 정적 값을 반환하거나 $thismatch하여 다른 경우에 다른 결과를 제공합니다.

이 경우 Red 및 Black 값으로 SuitColor Enum Type을 정의하고 대신 반환하는 것이 더 나은 데이터 모델링 방법입니다. 그러나 이는 이 예를 복잡하게 만듭니다.

위의 계층 구조는 논리적으로 다음 클래스 구조와 유사합니다(실제 실행 코드는 아니지만).

                  
<?php
interface Colorful
{
    public function color(): string;
}

final class Suit implements UnitEnum, Colorful
{
    public const Hearts = new self('Hearts');
    public const Diamonds = new self('Diamonds');
    public const Clubs = new self('Clubs');
    public const Spades = new self('Spades');

    private function __construct(public readonly string $name) {}

    public function color(): string
    {
        return match($this) {
            Suit::Hearts, Suit::Diamonds => 'Red',
            Suit::Clubs, Suit::Spades => 'Black',
        };
    }

    public function shape(): string
    {
        return "Rectangle";
    }

    public static function cases(): array
    {
        // Illegal method, because manually defining a cases() method on an Enum is disallowed.
        // See also "Value listing" section.
    }
}
?>
                  
                

메서드는 public, private 또는 protected일 수 있지만 실제로는 private 및 protected가 상속이 허용되지 않는 것과 동일합니다.