【问题标题】:Enum method match 'default'枚举方法匹配“默认”
【发布时间】:2022-01-24 15:28:16
【问题描述】:

我想知道是否有比我在 PHP 文档中找到的更丰富的“定义默认”匹配方式。以下来自https://www.php.net/manual/en/language.enumerations.methods.php

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',
        };
    }

}

以上并不是说明为什么我要问我所问的需要的最佳示例,还想不出更好的示例,但是为了这个问题,想象一下有 10 套西装, 9 黑色和 1 红色。看起来我必须在“黑色”的颜色匹配函数中重复 9 个案例......我希望(并在此处询问语法是否存在)有一种方法可以说“默认为“黑色” ”并且只使用“红色”来表示我明确地说是“红色”的那个。有点像我在 switch 语句中的表现。 PHP 枚举是否提供这样的语法?

【问题讨论】:

    标签: php enums php-8.1


    【解决方案1】:

    这不是关于 PHP 枚举,而是关于支持 default 情况的 match 表达式。

    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',
                default => 'Black'
            };
        }
    }
    
    echo Suit::Clubs->color(); // Black
    echo Suit::Hearts->color(); // Red
    

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2020-03-03
      • 2019-05-07
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2011-10-27
      • 2011-10-14
      • 1970-01-01
      相关资源
      最近更新 更多