Re: [Discussion] Implicitly backed enums
> On May 23, 2024, at 1:20 PM, Tim Düsterhus <[email protected]> wrote:
>
> Hi
>
> On 5/22/24 02:48, Aaron Piotrowski wrote:
>> Perhaps not as clean and easy as the functionality being built-in, but it gets the job
>> done.
>
> I would suggest to use the built-in functionality then.
>
> enum cases are literally just class constants, thus you can access them via the
> constant()
function or the dynamic class constant fetch syntax for PHP 8.3+ and check
> their existence with defined()
:
>
> https://3v4l.org/44goe
>
> <?php
>
> enum ExampleEnum
> {
> case ONE;
> case TWO;
> case THREE;
> }
>
> $caseName = 'ONE';
> var_dump(defined(ExampleEnum::class . "::{$caseName}"));
> var_dump(constant(ExampleEnum::class . "::{$caseName}"));
> var_dump(ExampleEnum::{$caseName});
>
> Outputs:
>
> bool(true)
> enum(ExampleEnum::ONE)
> enum(ExampleEnum::ONE)
>
> Best regards
> Tim Düsterhus
Hey Tim,
This solution is flawed. Not every constant is necessary an enum case. It also isn't type-safe
or as nice to read as tryFrom() and from() static methods.
Cheers,
Aaron Piotrowski
Thread (21 messages)