Hi all, > > I've submitted https://github.com/php/php-src/pull/11126 to add support > for final anonymous classes, though as noted by iluuu1994, it would > probably make more sense to just make all anonymous classes final by > default, what do you think? > > > > Extending an anonymous class is indeed possible (https://3v4l.org/pDFTL), > but it is a hack as best. If someone wants a non-final class, could they > not write a non-anonymous one? As a bonus, they wouldn’t need to > instantiate the class before referencing it. > > Indeed. The argument was that, if you need to give the anonymous class > a dedicated name through an alias to extend it, you might as well > declare a named class in the first place. > > In case somebody finds benefit in making anonymous classes open, it > seems more sensible to make them opt into openness, rather than > applying this behavior to all anonymous classes that are used as final > 99.9% of the time. Although I really don't think that is necessary. >
Fun fact: I wrote test code that extends anonymous classes recently. The typical test case is like this: $obj = new class() { public array $foo; }; $proxy = $this->createLazyGhost($obj::class, fn () => null); And createLazyGhost() generates a proxy class and returns an instance of it, see https://github.com/symfony/symfony/blob/1f8c5928a1445378eacbaf5b7e1636fdfa8610ed/src/Symfony/Component/VarExporter/Tests/LazyGhostTraitTest.php#L415-L438 Admittedly this is for convenience in writing test cases, but convenience is what many RFCs are about :) But anyway, there is a related idea I've had in my mind about anonymous classes that I'd like to throw in that conversation: Because they conceptually don't create a new type, I wonder if (final) anonymous classes could be allowed to extend final classes? In order to not allow hacking around and still create a type with class_alias(), we should forbid aliasing final anonymous classes IMHO. Then we could have this discussion about allowing finally anonymous classes to extend final classes. That'd be really useful in many situations where "final" is preventing end users from achieving what they want. Nicolas