枚举基础

Enum 类似 class,它和 class、interface、trait 共享同样的命名空间。 也能用同样的方式自动加载。 一个 Enum 定义了一种新的类型,它有固定、数量有限、可能的合法值。

<?php

enum Suit
{
case
Hearts;
case
Diamonds;
case
Clubs;
case
Spades;
}
?>

以上声明了新的枚举类型 Suit,仅有四个有效的值: Suit::HeartsSuit::DiamondsSuit::ClubsSuit::Spades。 变量可以赋值为以上有效值里的其中一个。 函数可以检测枚举类型,这种情况下只能传入类型的值。

<?php

function pick_a_card(Suit $suit)
{
/* ... */
}

$val = Suit::Diamonds;

// OK
pick_a_card($val);

// OK
pick_a_card(Suit::Clubs);

// TypeError: pick_a_card(): Argument #1 ($suit) must be of type Suit, string given
pick_a_card('Spades');
?>

一个枚举可以定义零个或多个case,且没有最大数量限制。 虽然零个 case 的 enum 没什么用处,但在语法上也是有效的。

枚举条目的语法规则适用于 PHP 中的任何标签,参见常量

默认情况下,枚举的条目(case)本质上不是标量。 就是说 Suit::Hearts 不等同于 "0"。 其实,本质上每个条目是该名称对象的单例。具体来说:

<?php

$a
= Suit::Spades;
$b = Suit::Spades;

$a === $b; // true

$a instanceof Suit; // true
?>

由于对象间的大小比较毫无意义,这也意味着 enum 值从来不会 <> 其他值。 当 enum 的值用于比较时,总是返回 false

这类没有关联数据的条目(case),被称为“纯粹条目”(Pure Case)。 仅包含纯粹 Case 的 Enum 被称为纯粹枚举(Pure Enum)。

枚举类型里所有的纯粹条目都是自身的实例。 枚举类型在内部的实现形式是一个 class。

所有的 case 有个只读的属性 name。 它大小写敏感,是 case 自身的名称。

<?php

print Suit::Spades->name;
// 输出 "Spades"
?>

It is also possible to use the defined() and constant() functions to check for the existence of or read an enum case if the name is obtained dynamically. This is, however, discouraged as using Backed enums should work for most use cases.

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top