无法使用 IOC 容器 laravel 实例化 class

Can`t instantiate class using IOC contatiner laravel

我正在尝试使用依赖注入来获取我的 class 的实例。 此 class 有自己的服务提供商,已在 app.php

中注册
 class Something
 {
      private $variable;

      public function __construct(string $variable)
      {
          $this->variable = $variable; 
      }
 }

这是服务提供商

class SomethingServiceProvider extends ServiceProvider
{

    public function boot()
    {

    }


    public function register()
    {
        $this->app->singleton('Something', function () {
            return new Something( 'test');
        });
    }
}

当我尝试在控制器中使用这个 class 实例时...

class TestController extends AppBaseController
{
    public function __construct(Something $something)
    {
        $this->something = $something;
    }
...

我收到错误:

"Unresolvable dependency resolving [Parameter #0 [ string $variable ]] in class Something at Container->unresolvablePrimitive(object(ReflectionParameter)) in Container.php (line 848) "

我想 YourServiceProvider::__construct 接受一个非类型化的 $app 实例。这意味着 Laravel 无法自动解析它。尝试输入它; public function __construct(Application $app) 使用正确的使用语句。

更多:https://laravel.com/docs/5.3/container#automatic-injection

当您注册要注入的内容时,您需要使用完全限定的 class 名称:

public function register()
{
    $this->app->singleton(Something::class, function () {
        return new Something( 'test');
    });
}

否则 Laravel 将尝试自动注入一些东西,这意味着它将首先尝试注入 Something 的依赖项,然后确定这是一个字符串并失败。