Re: proper anonymous classes?
| From: | Joe Watkins | Date: | Wed, 13 Feb 2019 08:16:13 +0000 |
| Subject: | Re: proper anonymous classes? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-104377@lists.php.net to get a copy of this message | ||
What you describe is first class support for classes, nothing much to do
with anonymous classes.
On Wed, 13 Feb 2019, 09:01 Rasmus Schultz <rasmus@mindplay.dk wrote:
> 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?
>