Re: [Discussion] Implicitly backed enums
| From: | Rowan Tommins [IMSoP] | Date: | Thu, 23 May 2024 10:38:21 +0000 |
| Subject: | Re: [Discussion] Implicitly backed enums | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-123410@lists.php.net to get a copy of this message | ||
On 22/05/2024 00:31, Larry Garfield wrote:
I could see an argument for auto-populating the backing value off the enum name if it's not specified, something like this: enum Options: string { case First; // This implicitly gets "First" case Second = '2nd'; }This reminds me of the short-hand key-value syntax that JavaScript allows, and people have occasionally requested equivalents for in PHP, where { foo } is equivalent to { 'foo': foo } The downside I see to all such short-hands is that they make it much harder to refactor safely, because the identifier and the string value are tied together. For instance, maybe you want to rename Options::First to Options::Legacy and Options::Second to Options::Modern so you edit the enum, and find all references in code: enum Options: string { case Legacy; case Modern = '2nd'; } But now everywhere you've serialized the old value of "First" is going to break, because the first case now has the implicit backing value of "Legacy" instead! To avoid this, you have to go ahead and specify all the backing values: enum Options: string { case Legacy = 'First'; case Modern = '2nd'; } Having to specify both the name and value in the first place makes that decision much more obvious, for what seems to me to be very little up-front cost. Regards, -- Rowan Tommins [IMSoP]