简体   繁体   English

使用PHP-DI将定义的参数注入构造函数时出现问题

[英]Trouble injecting defined parameters into constructor using PHP-DI

This may seen rudimentary but I cant seem to directly inject any parameters into my class constructor without using annotations. 这可能看起来很简单,但是我似乎无法在不使用注释的情况下直接将任何参数注入到我的类构造函数中。 Below is definition made and the class called 下面是定义,该类称为

    $shell->set('root','[Root Definition Here]');

    $shell->make('Namespace\To\Product');

    Class Product{

          public function __construct($root){
               //coding continues here
          }
    }

But I keep getting this error 但我不断收到这个错误

Uncaught exception 'Exception' with message 'Entry "Namespace\\To\\Product" cannot be resolved: Parameter $root of __construct() has no value defined or guessable 消息为“ Namespace \\ To \\ Product”的未捕获异常“ Exception”无法解析:__construct()的参数$ root没有定义或可猜测的值

However this issue will be resolved if I use annotations. 但是,如果使用批注,此问题将得到解决。 But I really want not to resort to annotations each time I'm injecting parameters. 但是我真的不想每次注入参数时都使用注解。

Whats the issue here? 这里有什么问题?

Thanks 谢谢

PHP-DI injects using the type-hints, not the parameter names. PHP-DI使用类型提示而不是参数名称进行注入。 So it would work if $root had a type-hint (eg Foo\\Bar $root ), but as it is now it can't work. 因此,如果$root具有类型提示(例如Foo\\Bar $root ),它将起作用,但由于现在它不起作用。

You have to define the parameter manually: 您必须手动定义参数:

$container->set(
    'Namespace\To\Product',
    DI\object()->constructor(DI\get('root')
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM