The point of an ENUM is precisely to restrict options within a certain range.
Assume you declared `ErrorCode` with `SOMETHING_BROKE` and `PEBKAC` as possible enumeration values. If you can (somewhere, anywhere in the code) check `instanceof ErrorCode`, then you know it can only be `SOMETHING_BROKE` and `PEBKAC`, and you can write logic around it accordingly. This restriction/assumption is what makes ENUMs powerful: expanding pre-existing enums would eliminate this very core design principle, since you may now no longer have an `ErrorCode`, but some child class designed somewhere that may not even be under your control. Greets, Marco Pivetta https://mastodon.social/@ocramius https://ocramius.github.io/ On Wed, 29 Mar 2023 at 10:31, Rokas Šleinius <rave...@gmail.com> wrote: > Enums were a very useful addition to PHP, however one aspect of them is > neither > explicitly documented - or seemingly even talked about. > > Enums were implemented as final so they cannot be extended nor can extend > anything else. > > From a user perspective it's surprising - and actually limiting. > > USAGE EXAMPLE: > I am making an error management system: each error presented to the user > must have a unique code visible. > > ```php > class SystemError > { > public function __construct( > private string $errorText, > private ErrorCode $code > ) { > } > > public function __toString(): > { > return $this->errorText . ' ' . $this->code->toString(); > } > } > // ... > > enum ErrorCode > { > case Code_1; > case Code_2; > > public function toString(): string > { > return 'Error code:' . substr($this->name, strlen('Code_')); > } > } > ``` > > Now I want to modify it to support different modules with different > namespaces for > errors, e.g. an ApiError, simple enough: > > ```php > enum BaseErrorCode > { > // ... > } > > enum ErrorCode extends BaseErrorCode > { > case Code_1; > case Code_2; > > // ... > } > > enum ApiErrorCode extends BaseErrorCode { > // ... > function toString(): string > { > return 'Error code:API-' . substr($this->name, strlen('Code_')); > } > } > ``` > > This results in a syntax error. > > PROPOSAL: > > Enums should be able to extend other enums. > > For a complete wishlist, add: > * abstract enums; > * enums allowed to implement interfaces; > > However since I have no experience in PHP source code, I can only > provide the test suite for a possible PR this might have :( > > Do you think this is likely to get implemented? > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: https://www.php.net/unsub.php > >