proper anonymous classes?

From: Date: Wed, 13 Feb 2019 08:01:21 +0000
Subject: proper anonymous classes?
Groups: php.internals 
Request: Send a blank email to internals+get-104376@lists.php.net to get a copy of this message
The fact that the anonymous class syntax defines a class *and* immediately constructs an instance is quite annoying. For one, this is quite incompatible with DI containers' ability to resolve constructor arguments. Lets say you DI container can register a named component by merely referencing a class that uses constructor injection - so lets say this works: class MyController { public function __construct(MyService $service) { // ... } } $container->register("my-controller", MyController::class); Now I want to register an anonymous class, for example as part of an integration test-suite, which is common enough: $container->register("my-controller", new class { public function __construct(MyService $service) { // ... } }); This doesn't work, because you're expected to actually pass the constructor arguments immediately - because you can only define an anonymous class while immediately creating an instance. What I really want is just an anonymous class - not an instance, so: $container->register("my-controller", class { public function __construct(MyService $service) { // ... } }); The question is, what would a class expression without the new keyword evaluate to? Since we normally reference classes with just a class-name, I guess I'd expect a string, like you'd get from the ::class constant. Any hope for something like that?

« previous php.internals (#104376) next »