枚举概览

(PHP 8 >= 8.1.0)

枚举,或称 “Enum”,能够让开发者自定义类型为一系列可能的离散值中的一个。 在定义领域模型中很有用,它能够“隔离无效状态”(making invalid states unrepresentable)。

枚举以各种不同功能的形式出现在诸多语言中。 在 PHP 中, 枚举是一种特殊类型的对象。Enum 本身是一个类(Class), 它的各种条目(case)是这个类的单例对象,意味着也是个有效对象 —— 包括类型的检测,能用对象的地方,也可以用它。

最常见的枚举例子是内置的 boolean 类型, 该枚举类型有两个有效值 truefalse。 Enum 使开发者能够任意定义出用户自己的、足够健壮的枚举。

add a note add a note

User Contributed Notes 1 note

up
2
Hayley Watson
1 year ago
It's important to notice that the description here doesn't describe Enum values as being constants. Some languages, like C, C++, and C#, think of an enum as a list of named integers, and working with enums in those languages is just working with integers. PHP does not do that.

In the same way that PHP's booleans are their own type and not just constants with integer values 1 and 0, an Enum is its own type. It's not a bunch of integers (or strings) that have been given names, and shouldn't be thought of or used as such.

An Enum only needs to be backed by some primitive value like an integer or string if you need to communicate it outside the program (a message, UI, db storage, wire protocol, etc) where it has to be converted from/to its native PHP value (this is addressed again on the Backed Enumerations page). If you're converting back and forth between Enums and their backing values inside your own program to get anything done then you might be missing the point of Enums.

You might want more structure to your Enum than just a pure set of distinct but otherwise nondescript values (you might at least want them to be ordered). But all that carry-on should be encapsulated within the Enum class itself via additional methods.
To Top