________________________________ From: Rowan Tommins <rowan.coll...@gmail.com> Sent: Thursday, February 9, 2023 12:56 AM To: internals@lists.php.net <internals@lists.php.net> Subject: Re: [PHP-DEV] RFC proposal: values getter in BackedEnum
On Thu, 9 Feb 2023 at 01:30, Sergii Shymko <ser...@shymko.net> wrote: > I'd like to propose an improvement to backed enumerations introduced in > PHP 8.1. > When using enums, it's very common to get all values using the following > boilerplate: > $enumValues = array_map( > fn (\BackedEnum $case) => $case->value, > ExampleEnum::cases() > ); > Since the value is exposed as a public property, there is already a much shorter way of writing this: $enumValues = array_column(BackedEnum::cases(), 'value'); As I pointed out in a StackOverflow answer [ https://stackoverflow.com/a/71235974/157957], you can get the case name the same way, and use different arguments to array_column to get combinations like a look up table from value to name: $nameToValue = array_column(BackedEnum::cases(), 'name', 'value'); Regards, -- Rowan Tommins [IMSoP] Ho Rowan, Thanks for pointing out a shorter way of coding this via array_column()! While it's good to know and an improvement, I think, the proposal still stands. BackedEnum::values() is much more convenient than array_column(BackedEnum::cases(), 'value'); And the potential for the performance optimization to return a constant is still there. IMO, other variations of array_column() returning a map don't seem to be useful in practice. Particularly, what is knowing the case name good for? Do you propose to resolve it to the case instance like so? $case = constant(ExampleEnum::class . '::' . $caseName); My understanding is that backed enums serve the purpose of doing the mapping. Regards, Sergii