[php-src] Issue #12150: Allow enums to have readonly properties a la Java enums

From: Date: Thu, 07 Sep 2023 11:31:05 +0000
Subject: [php-src] Issue #12150: Allow enums to have readonly properties a la Java enums
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-245357@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/12150 Author: dktapps ### Description Properties are currently banned in enums, I assume because readonly wasn't a thing when they were implemented, and the RFC authors wanted to make sure enums were readonly. With the introduction of enums, it should be possible to associate properties with enums, a la Java enums. This can currently be achieved with a boilerplaty mess like this: ```php <?php enum NativeEnum{ case ONE; case TWO; case THREE; public function p1() : int{ return NativeEnumProperties::getMetadata($this)->p1; } public function p2() : int{ return NativeEnumProperties::getMetadata($this)->p2; } } class NativeEnumProperties{ /** @var self[] */ private static array $metadata = []; public static function getMetadata(NativeEnum $case) : self{ return self::$metadata[$case->name] ??= match($case){ NativeEnum::ONE => new self(1, 1), NativeEnum::TWO => new self(2, 2), NativeEnum::THREE => new self(3, 3), }; } private function __construct( public readonly int $p1, public readonly int $p2, ){} } var_dump(NativeEnum::ONE->p1()); var_dump(NativeEnum::ONE->p2()); ``` I'm envisioning something like this (again, inspired by Java): ```php enum NativeEnum{ case ONE(1, 1); case TWO(2, 2); case THREE(3, 3); private function __construct( public readonly int $p1, public readonly int $p2, ){} } var_dump(NativeEnum::ONE->p1); //1 ``` I'm not exactly sure how this would work in practice though. In Java, it permits full mutation of the enum objects, which isn't allowed in PHP, and that should probably remain so. Perhaps if enum classes are considered completely readonly, (implying readonly class NativeEnum a la PHP 8.2)? It's possible to preprocess the second example into something resembling the first, but it would be great if PHP supported this directly :)

« previous php.bugs (#245357) next »