CakeFest 2024: The Official CakePHP Conference

列挙型の概要

(PHP 8 >= 8.1.0)

列挙型(Enumerations) または Enum を使うと、 開発者は取りうる値を限定した独自の型を定義できます。 これによって、"不正な状態を表現できなくなる" ので、 ドメインモデルを定義する時に特に役立ちます。

列挙型は、多くのプログラミング言語に備わっており、 様々な異なる機能があります。 PHP では、列挙型は特別な種類のオブジェクトです。 列挙型そのものはクラスですし、そこで定義される case は全て、 そのクラスのインスタンスです。 これは、列挙型で定義される case は有効なオブジェクトであり、 型チェックを含む、オブジェクトが使えるあらゆる場所で使えるということです。

列挙型のもっとも有名な例は、組み込みの論理型(boolean) です。 これは、有効な値 truefalse を持つ列挙型です。 列挙型によって、開発者は任意の値の一覧を、 安定した形で定義できるようになります。

add a note

User Contributed Notes 1 note

up
-6
Hayley Watson
11 months 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