Enumerations Enumerations overview Enumerations, or "Enums" allow a developer to define a custom type that is limited to one of a discrete number of possible values. That can be especially helpful when defining a domain model, as it enables "making invalid states unrepresentable." Enums appear in many languages with a variety of different features. In PHP, Enums are a special kind of object. The Enum itself is a class, and its possible cases are all single-instance objects of that class. That means Enum cases are valid objects and may be used anywhere an object may be used, including type checks. The most popular example of enumerations is the built-in boolean type, which is an enumerated type with legal values &true; and &false;. Enums allows developers to define their own arbitrarily robust enumerations. Basic enumerations Enums are similar to classes, and share the same namespaces as classes, interfaces, and traits. They are also autoloadable the same way. An Enum defines a new type, which has a fixed, limited number of possible legal values. ]]> This declaration creates a new enumerated type named Suit, which has four and only four legal values: Suit::Hearts, Suit::Diamonds, Suit::Clubs, and Suit::Spades. Variables may be assigned to one of those legal values. A function may be type checked against an enumerated type, in which case only values of that type may be passed. ]]> An Enumeration may have zero or more case definitions, with no maximum. A zero-case enum is syntactically valid, if rather useless. For Enumeration cases, the same syntax rules apply as to any label in PHP, see Constants. By default, cases are not intrinsically backed by a scalar value. That is, Suit::Hearts is not equal to "0". Instead, each case is backed by a singleton object of that name. That means that: ]]> It also means that enum values are never < or > each other, since those comparisons are not meaningful on objects. Those comparisons will always return false when working with enum values. This type of case, with no related data, is called a "Pure Case." An Enum that contains only Pure Cases is called a Pure Enum. All Pure Cases are implemented as instances of their enum type. The enum type is represented internally as a class. All Cases have a read-only property, name, that is the case-sensitive name of the case itself. name; // prints "Spades" ?> ]]> Backed enumerations By default, Enumerated Cases have no scalar equivalent. They are simply singleton objects. However, there are ample cases where an Enumerated Case needs to be able to round-trip to a database or similar datastore, so having a built-in scalar (and thus trivially serializable) equivalent defined intrinsically is useful. To define a scalar equivalent for an Enumeration, the syntax is as follows: ]]> A case that has a scalar equivalent is called a Backed Case, as it is "Backed" by a simpler value. An Enum that contains all Backed Cases is called a "Backed Enum." A Backed Enum may contain only Backed Cases. A Pure Enum may contain only Pure Cases. A Backed Enum may be backed by types of int or string, and a given enumeration supports only a single type at a time (that is, no union of int|string). If an enumeration is marked as having a scalar equivalent, then all cases must have a unique scalar equivalent defined explicitly. There are no auto-generated scalar equivalents (e.g., sequential integers). Backed cases must be unique; two backed enum cases may not have the same scalar equivalent. However, a constant may refer to a case, effectively creating an alias. See Enumeration constants. Equivalent values must be literals or literal expressions. Constants and constant expressions are not supported. That is, 1 + 1 is allowed, but 1 + SOME_CONST is not. Backed Cases have an additional read-only property, value, which is the value specified in the definition. value; // Prints "C" ?> ]]> In order to enforce the value property as read-only, a variable cannot be assigned as a reference to it. That is, the following throws an error: value; // Error: Cannot acquire reference to property Suit::$value ?> ]]> Backed enums implement an internal BackedEnum interface, which exposes two additional methods: from(int|string): self will take a scalar and return the corresponding Enum Case. If one is not found, it will throw a ValueError. This is mainly useful in cases where the input scalar is trusted and a missing enum value should be considered an application-stopping error. tryFrom(int|string): ?self will take a scalar and return the corresponding Enum Case. If one is not found, it will return null. This is mainly useful in cases where the input scalar is untrusted and the caller wants to implement their own error handling or default-value logic. The from() and tryFrom() methods follow standard weak/strong typing rules. In weak typing mode, passing an integer or string is acceptable and the system will coerce the value accordingly. Passing a float will also work and be coerced. In strict typing mode, passing an integer to from() on a string-backed enum (or vice versa) will result in a TypeError, as will a float in all circumstances. All other parameter types will throw a TypeError in both modes. value; $suit = Suit::tryFrom('A') ?? Suit::Spades; // Invalid data returns null, so Suit::Spades is used instead. print $suit->value; ?> ]]> Manually defining a from() or tryFrom() method on a Backed Enum will result in a fatal error. Enumeration methods Enums (both Pure Enums and Backed Enums) may contain methods, and may implement interfaces. If an Enum implements an interface, then any type check for that interface will also accept all cases of that Enum. 'Red', Suit::Clubs, Suit::Spades => 'Black', }; } // Not part of an interface; that's fine. public function shape(): string { return "Rectangle"; } } function paint(Colorful $c) { ... } paint(Suit::Clubs); // Works print Suit::Diamonds->shape(); // prints "Rectangle" ?> ]]> In this example, all four instances of Suit have two methods, color() and shape(). As far as calling code and type checks are concerned, they behave exactly the same as any other object instance. On a Backed Enum, the interface declaration goes after the backing type declaration. 'Red', Suit::Clubs, Suit::Spades => 'Black', }; } } ?> ]]> Inside a method, the $this variable is defined and refers to the Case instance. Methods may be arbitrarily complex, but in practice will usually return a static value or match on $this to provide different results for different cases. Note that in this case it would be a better data modeling practice to also define a SuitColor Enum Type with values Red and Black and return that instead. However, that would complicate this example. The above hierarchy is logically similar to the following class structure (although this is not the actual code that runs): 'Red', Suit::Clubs, Suit::Spades => 'Black', }; } public function shape(): string { return "Rectangle"; } public static function cases(): array { // Illegal method, because manually defining a cases() method on an Enum is disallowed. // See also "Value listing" section. } } ?> ]]> Methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed. Enumeration static methods Enumerations may also have static methods. The use for static methods on the enumeration itself is primarily for alternative constructors. E.g.: static::Small, $cm < 100 => static::Medium, default => static::Large, }; } } ?> ]]> Static methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed. Enumeration constants Enumerations may include constants, which may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed. An enum constant may refer to an enum case: ]]> Traits Enumerations may leverage traits, which will behave the same as on classes. The caveat is that traits used in an enum must not contain properties. They may only include methods and static methods. A trait with properties will result in a fatal error. 'Red', Suit::Clubs, Suit::Spades => 'Black', }; } } ?> ]]> Enum values in constant expressions Because cases are represented as constants on the enum itself, they may be used as static values in most constant expressions: property defaults, static variable defaults, parameter defaults, global and class constant values. They may not be used in other enum case values, but normal constants may refer to an enum case. However, implicit magic method calls such as ArrayAccess on enums are not allowed in static or constant definitions as we cannot absolutely guarantee that the resulting value is deterministic or that the method invocation is free of side effects. Function calls, method calls, and property access continue to be invalid operations in constant expressions. ]]> Differences from objects Although Enums are built on classes and objects, they do not support all object-related functionality. In particular, Enum cases are forbidden from having state. Constructors and Destructors are forbidden. Inheritance is not supported. Enums may not extend or be extended. Static or object properties are not allowed. Cloning an Enum case is not supported, as cases must be singleton instances Magic methods, except for those listed below, are disallowed. The following object functionality is available, and behaves just as it does on any other object: Public, private, and protected methods. Public, private, and protected static methods. Public, private, and protected constants. Enums may implement any number of interfaces. Enums and cases may have attributes attached to them. The TARGET_CLASS target filter includes Enums themselves. The TARGET_CLASS_CONST target filter includes Enum Cases. __call, __callStatic, and __invoke magic methods __CLASS__ and __FUNCTION__ constants behave as normal The ::class magic constant on an Enum type evaluates to the type name including any namespace, exactly the same as an object. The ::class magic constant on a Case instance also evaluates to the Enum type, as it is an instance of that type. Additionally, enum cases may not be instantiated directly with new, nor with ReflectionClass::newInstanceWithoutConstructor in reflection. Both will result in an error. newInstanceWithoutConstructor() // Error: Cannot instantiate enum Suit ?> ]]> Value listing Both Pure Enums and Backed Enums implement an internal interface named UnitEnum. UnitEnum includes a static method cases(). cases() returns a packed array of all defined Cases in the order of declaration. ]]> Manually defining a cases() method on an Enum will result in a fatal error. Serialization Enumerations are serialized differently from objects. Specifically, they have a new serialization code, "E", that specifies the name of the enum case. The deserialization routine is then able to use that to set a variable to the existing singleton value. That ensures that: ]]> On deserialization, if an enum and case cannot be found to match a serialized value a warning will be issued and false returned. If a Pure Enum is serialized to JSON, an error will be thrown. If a Backed Enum is serialized to JSON, it will be represented by its value scalar only, in the appropriate type. The behavior of both may be overridden by implementing JsonSerializable. For print_r, the output of an enum case is slightly different from objects to minimize confusion. Bar ) Baz Enum:int { [name] => Beep [value] => 5 } */ ?> ]]> &reftitle.examples; Basic limited values ]]> The query() function can now proceed safe in the knowledge that $order is guaranteed to be either SortOrder::ASC or SortOrder::DESC. Any other value would have resulted in a TypeError, so no further error checking or testing is needed. Advanced exclusive values 'Pending', static::Active => 'Active', static::Suspended => 'Suspended', static::CanceledByUser => 'Canceled by user', }; } } ?> ]]> In this example, a user's status may be one of, and exclusively, UserStatus::Pending, UserStatus::Active, UserStatus::Suspended, or UserStatus::CanceledByUser. A function can type a parameter against UserStatus and then only accept those four values, period. All four values have a label() method, which returns a human-readable string. That string is independent of the "machine name" scalar equivalent string, which can be used in, for example, a database field or an HTML select box. %s\n', $case->value, $case->label()); } ?> ]]>