关于php:PHP枚举

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中蕴含属性,只能存在办法、静态方法

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理