GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing wiki.php.net — PHP: rfc:enumerations rfc:enumerations
PHP RFC: Enumerations
IntroductionThis RFC introduces Enumerations to PHP. The scope of this RFC is limited to “unit enumerations,” that is, enumerations that are themselves a value, rather than simply a fancy syntax for a primitive constant, and do not include additional associated information. This capability offers greatly expanded support for data modeling, custom type definitions, and monad-style behavior. Enums enable the modeling technique of “make invalid states unrepresentable,” which leads to more robust code with less need for exhaustive testing. Many languages have support for enumerations of some variety. A survey we conducted of various languages found that they could be categorized into three general groups: Fancy Constants, Fancy Objects, and full Algebraic Data Types (ADTs). This RFC is part of a larger effort to introduce full Algebraic Data Types. It implements the “Fancy Objects” variant of enumerations in such a way that it may be extended to full ADTs by future RFCs. It draws both conceptually and semantically from Swift, Rust, and Kotlin, although it is not directly modeled on either.
The most popular case of enumerations is Proposal
Enumerations are built on top of classes and objects. That means, except where otherwise noted, “how would Enums behave in situation X” can be answered “the same as any other object instance.” They would, for example, pass an Basic enumerations
This RFC introduces a new language construct, enum Suit { case Hearts; case Diamonds; case Clubs; case Spades; }
This declaration creates a new enumerated type named function pick_a_card(Suit $suit) { ... } $val = Suit::Diamonds; pick_a_card($val); // OK pick_a_card(Suit::Clubs); // OK pick_a_card('Spades'); // TypeError: pick_a_card(): Argument #1 ($suit) must be of type Suit, string given
An Enumeration may have zero or more
By default, cases are not intrinsically backed by a scalar value. That is, $a = Suit::Spades; $b = Suit::Spades; $a === $b; // true $a instanceof Suit; // true
It also means that enum values are never 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, print Suit::Spades->name; // prints "Spades" Backed EnumsBy 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: enum Suit: string { case Hearts = 'H'; case Diamonds = 'D'; case Clubs = 'C'; case Spades = 'S'; } 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
Equivalent values must be literals or literal expressions. Constants and constant expressions are not supported. That is,
Value Cases have an additional read-only property, print Suit::Clubs->value; // Prints "C"
In order to enforce the $suit = Suit::Clubs; $ref = &$suit->value; // Error: Cannot acquire reference to property Suit::$value
Backed enums implement an internal
The “tryX” idiom is common in C# and Rust (albeit in somewhat different ways) to indicate that the result may be null/optional. It would be new to PHP, but not incompatible with any current conventions.
The $record = get_stuff_from_database($id); print $record['suit']; $suit = Suit::from($record['suit']); // Invalid data throws a ValueError: "X" is not a valid scalar value for enum "Suit" print $suit->value; $suit = Suit::tryFrom('A') ?? Suit::Spades; // Invalid data returns null, so Suit::Spades is used instead. print $suit->value;
Manually defining a Enumerated MethodsEnums (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. interface Colorful { public function color(): string; } enum Suit implements Colorful { case Hearts; case Diamonds; case Clubs; case Spades; // Fulfills the interface contract. public function color(): string { return match($this) { Suit::Hearts, Suit::Diamonds => '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
Inside a method, the
Methods may be arbitrarily complex, but in practice will usually return a static value or
Note that in this case it would be a better data modeling practice to also define a The above hierarchy is logically similar to the following class structure (although this is not the actual code that runs): interface Colorful { public function color(): string; } final class Suit implements UnitEnum, Colorful { public const Hearts = new self('Hearts'); public const Diamonds = new self('Diamonds'); public const Clubs = new self('Clubs'); public const Spades = new self('Spades'); private function __construct(public string $name) {} public function color(): string { return match($this) { Suit::Hearts, Suit::Diamonds => 'Red', Suit::Clubs, Suit::Spades => 'Black', }; } public function shape(): string { return "Rectangle"; } public static function cases(): array { // See below. } } The case instance objects may be assigned to constants because they are created internally in the engine rather than in user-space. Additionally, the differentiating flag for each case is not actually a constructor parameter. Methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed. Enumeration static methodsEnumerations may also have static methods. The use for static methods on the enumeration itself is primarily for alternative constructors. E.g.: enum Size { case Small; case Medium; case Large; public static function fromLength(int $cm) { return match(true) { $cm < 50 => 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 constantsEnumerations 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: enum Size { case Small; case Medium; case Large; public const Huge = self::Large; } Traits
Enumerations may leverage traits, which will behave the same as on classes. The caveat is that traits interface Colorful { public function color(): string; } trait Rectangle { public function shape(): string { return "Rectangle"; } } enum Suit implements Colorful { use Rectangle; case Hearts; case Diamonds; case Clubs; case Spades; public function color(): string { return match($this) { Suit::Hearts, Suit::Diamonds => 'Red', Suit::Clubs, Suit::Spades => 'Black', }; } } Enum values in constant expressionsBecause 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 due to implementation complexity. (That restriction may be lifted in the future, but since they can be used by constants on an enum it is not a significant limitation.) 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. In code: // This is an entirely legal Enum definition. enum Direction implements ArrayAccess { case Up; case Down; public function offsetGet($val) { ... } public function offsetExists($val) { ... } public function offsetSet($val) { throw new Exception(); } public functiond offsetUnset($val) { throw new Exception(); } } class Foo { // This is allowed. const Bar = Direction::Down; // This is disallowed, as it may not be deterministic. const Bar = Direction::Up['short']; // Fatal error: Cannot use [] on enums in constant expression } // This is entirely legal, because it's not a constant expression. $x = Direction::Up['short']; Comparison to objectsAlthough Enums are implemented using classes under the hood and share much of their semantics, some object-style functionality is forbidden. These either do not make sense in the scope of enums, their value is debatable (but could be re-added in the future), or their semantics are unclear. Specifically, the following features of objects are not allowed on enumerations:
If you need any of that functionality, classes as they already exist are the superior option. The following object functionality is available, and behaves just as it does on any other object:
The
Additionally, enum cases may not be instantiated directly with $clovers = new Suit(); // Error: Cannot instantiate enum Suit $mace = (new ReflectionClass(Suit::class))->newInstanceWithoutConstructor() // Error: Cannot instantiate enum Suit Value listing
Both Pure Enums and Backed Enums implement an internal interface named Suit::cases(); // Produces: [Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit:Spades]
Manually defining a Non-iterable Enums are not yet supported, but are expected to be part of the future ADT/Tagged Union RFC. (Those will not have a finite set of possible values.)
Note that SerializationEnumerations 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: Suit::Hearts === unserialize(serialize(Suit::Hearts)); print serialize(Suit::Hearts); // E:11:"Suit:Hearts";
On deserialization, if an enum and case cannot be found to match a serialized value a warning will be issued and
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
For enum Foo { case Bar; } enum Baz: int { case Beep = 5; } print_r(Foo::Bar); print_r(Baz::Beep); Foo Enum (
[name] => Bar
)
Baz Enum:int {
[name] => Beep
[value] => 5
}
Attributes
Enums and cases may have attributes attached to them, like any other language construct. The No engine-defined attributes are included. User-defined attributes can do whatever. Match expressions
$val = Suit::Diamonds; $str = match ($val) { Suit::Spades => "The swords of a soldier", Suit::Clubs => "Weapons of war", Suit::Diamonds => "Money for this art", default => "The shape of my heart", }
This usage requires no modification of SplObjectStorage and WeakMaps
As objects, Enum cases cannot be used as keys in an array. However, they can be used as keys in a
This usage requires no modification to Reflection
Enums are reflectable using a class ReflectionEnum extends ReflectionClass { // Returns true if there is a Case defined with that name. // For instance, ''$r->hasCase('Hearts')'' returns true. public function hasCase(string $name): bool {} // Returns an array of ReflectionEnumPureCase|ReflectionEnumBackedCase objects. public function getCases(): array {} // Returns a single reflection object for the corresponding case. // If not found, throws, ReflectionException. public function getCase(string $name): ReflectionEnumPureCase|ReflectionEnumBackedCase // True if this enum has a backing type, false otherwise. public function isBacked(): bool {} // Returns the type of the backing values of this enum, if any. // On a Pure Enum, returns null. public getBackingType(): ?ReflectionType {} } class ReflectionEnumUnitCase extends ReflectionClassConstant { // Pre-existing. This will return the corresponding enum instance for this case. public function getValue() {} // Returns the ReflectionEnum instance for this case's enum class. public function getEnum(): ReflectionEnum {} } class ReflectionEnumBackedCase extends ReflectionEnumUnitCase { // Returns the scalar equivalent defined for the case. public function getBackingValue(): int|string {} }
Additionally, a new function ExamplesBelow are a few examples of Enums in action. Basic limited valuesenum SortOrder { case ASC; case DESC; } function query($fields, $filter, SortOrder $order = SortOrder::ASC) { ... }
The Advanced Exclusive valuesenum UserStatus: string { case Pending = 'P'; case Active = 'A'; case Suspended = 'S'; case CanceledByUser = 'C'; public function label(): string { return match($this) { static::Pending => '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,
All four values have a foreach (UserStatus::cases() as $case) { printf('<option value="%s">%s</option>\n', $case->value, $case->label()); } New interfacesAs noted above, this RFC defines two additional internal interfaces. These interfaces are available to make it possible for user code to determine if a given object is an enumeration, and if so what type. User code may not implement or extend these interfaces directly. interface UnitEnum { public string $name; public static function cases(): array; } interface BackedEnum extends UnitEnum { public string $value; public static function from(int|string $scalar): static; public static function tryFrom(int|string $scalar): ?static; } Backward Incompatible Changes
Thanks to a clever trick from Nikita (discussed after the RFC was approved), “enum” is not a reserved word on its own. That means it is still a legal name for a class/interface/trait at this time. It will likely be converted into a full keyword at some point in the future, but this RFC does not specify that timeline. As a side effect, comments are not supported between “enum” and the Enum name, which is of little consequence in practice.
The global scoped internal interfaces
The global function Future ScopeSee the Algebraic data types (Meta RFC) document. Grouped syntaxIt would be possible, in the simple case, to allow multiple cases to be defined together, like so: enum Suit { case Hearts, Diamonds, Clubs, Spades; } However, that may cause syntactic issues with the planned addition of tagged unions, which may or may not end up including per-case methods. Until that future extension is settled, we opted to skip this syntactic optimization. Grouped syntaxes have a somewhat controversial history anyway (they're not universally loved, and often unused entirely in many situations), and it's easy enough to add later if needed, so we have omitted that shorthand at this time. Once the dust settles, they may get added in the future. Enums as array keysBecause they are objects, enum cases may not be used as keys in an associative array. It may be possible to support that in the future, but that is not covered at this time. For now, SplObjectStorage and WeakMaps are good enough. Enum Sets
An enum set is the logical OR of two other cases. For instance, Adding support for enum sets is a possibility for a future RFC, should an appropriate implementation be determined. Auto-scalar conversion
Whether or not a Backed Enum can be viewed as “close enough” to its corresponding scalar value is debatable, and of debatable value. For instance, is a string-backed enum The optimal behavior here, if any, will likely not become apparent until enums see widespread use. We have therefore opted to omit all auto-conversion at this time. If clear and compelling use cases for auto-conversion appear in the future, later PHP versions can re-introduce such auto-conversion in a more targeted, well-informed way. Magic read-methods
The
If when the dust settles it appears that Constant-reference expression values
Currently, a Backed Enum value may only be a constant literal or an arithmetic expression involving only constant literals. They cannot reference other constant symbols, such as VotingThis is a simple yes/no vote to include Enumerations. 2/3 required to pass. Voting started 2021-02-03 and closes 2021-02-17.
Referencesrfc/enumerations.txt · Last modified: by ilutov
Table of Contents | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |