Re: [Discussion] Implicitly backed enums

From: Date: Thu, 23 May 2024 18:34:28 +0000
Subject: Re: [Discussion] Implicitly backed enums
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-123421@lists.php.net to get a copy of this message
> On May 23, 2024, at 1:20 PM, Tim Düsterhus <tim@bastelstu.be> 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

« previous php.internals (#123421) next »