Enumerations (enums) were introduced in PHP 8.1 (enumerations). The RFC specified that magic methods other than __call(), __callStatic(), and __invoke() would not be permitted in enums, noting that most other magic methods involve state, which enum instances do not have. However, the exclusion also applies to __toString(), which does not need to involve state. This RFC proposes allowing the __toString() magic method on enums.
<?php enum Foo: string { case Bar = "Baz"; public function __toString() { return __CLASS__ . '::' . $this->name . ' = ' . $this->value; } } echo Foo::Bar; // produces "Foo::Bar = Baz" ?>
The error when trying to implement __toString() on an enumeration is removed. The default validation of that magic method (visibility, arguments, return type) is applied if the method is present, and if present the Stringable interface is added as normal (stringable).
Simple example for a unit enum:
<?php enum Foo { case Bar; public function __toString() { return $this->name . ' is a case of the ' . __CLASS__ . ' enum'; } } echo Foo::Bar; // produces "Bar is a case of the Foo enum" ?>
Simple example for a backed enum:
<?php enum Foo: string { case Bar = "Baz"; public function __toString() { return __CLASS__ . '::' . $this->name . ' = ' . $this->value; } } echo Foo::Bar; // produces "Foo::Bar = Baz" ?>
There should be no backward incompatible changes - this is the removal of an existing error.
Next PHP version (PHP 8.6).
Analysis tools that warn about trying to define a __toString() method on enums would need to be updated to not warn when the code is for PHP 8.6+.
There are some built-in enums, e.g. \Random\IntervalBoundary - in the future, they may have __toString() methods, but this RFC does not include such additions.
Perhaps some of the other magic methods should also be allowed.
Please consult the php/policies repository for the current voting guidelines.
After the RFC is implemented, this section should contain:
Links to external references, discussions, or RFCs.
Keep this updated with features that were discussed on the mail lists.
If there are major changes to the initial proposal, please include a short summary with a date or a link to the mailing list announcement here, as not everyone has access to the wikis' version history.