关于php:PHP枚举

6次阅读

共计 1455 个字符,预计需要花费 4 分钟才能阅读完成。

PHP8.1 新增

根底

Enum 相似 class

枚举的 case 能够定义 0 个或多个

枚举间比照没有意义,总是返回 false。case 是能够比照的

<?php

enum Colors
{
     case Red;
     case Blue;
     case Green;

     public function getColor(): string
     {return $this->name;}
 }

function paintColor(Colors $colors): void
{echo "Paint :" . $colors->getColor() . PHP_EOL;
 }

paintColor(Colors::Red);
paintColor(Colors::Green);
paintColor(Colors::Blue);

/*
     output :
     ------------------------
     Paint : Red
     Paint : Green
     Paint : Blue
  */

回退枚举

case 默认是类实现的,case 能够赋值标量,这时 case 的类型会由简单类型转为简略类型,这种称为回退

回退枚举只有一个 value 属性

回退枚举实现了 BackedEnuminterface,额定裸露了from()tryFrom() 办法

枚举值必须是确定的,不能是可变的

<?php
enum Suit: string
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

print Suit::Clubs->value;
print Suit::from('H');
print Suit::tryFrom('XX') ?? Suit::Hearts;

枚举办法

枚举能定义本人的办法、静态方法,也能实现 interface,然而不反对继承

因为不反对继承所以拜访修饰符没什么用,都有 public 即可

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

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

    // 满足 interface 契约。public function color(): string
    {return match($this) {
            Suit::Hearts, Suit::Diamonds => 'Red',
            Suit::Clubs, Suit::Spades => 'Black',
        };
    }

    // 不是 interface 的一部分;也没问题
    public function shape(): string
    {return "Rectangle";}
    
    // 静态方法
    public static function fromLength(int $cm): static
    {return match(true) {
            $cm < 50 => static::Hearts,
            $cm < 100 => static::Diamonds,
            default => static::Clubs,
        };
    }
    
}

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

paint(Suit::Clubs);  // 失常

print Suit::Diamonds->shape(); // 输入 "Rectangle"

枚举常量

<?php
enum Size
{
    case Small;
    case Medium;
    case Large;

    public const Huge = self::Large;
}

应用 Trait

在 enum 中应用 trait 时,不容许 trait 中蕴含属性,只能存在办法、静态方法

正文完
 0