您无法同时创建单例和使用参数。这是来自Container.php的相关代码:
// If an instance of the type is currently being managed as a singleton we'll
// just return an existing instance instead of instantiating new instances
// so the developer can keep using the same objects instance every time.
if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
return $this->instances[$abstract];
}
然后
// If the requested type is registered as a singleton we'll want to cache off
// the instances in "memory" so we can return it later without creating an
// entirely new instance of an object on each subsequent request for it.
if ($this->isShared($abstract) && ! $needsContextualBuild) {
$this->instances[$abstract] = $object;
}
请注意,如果实例是使用 makeWith 和参数创建的(除了具有上下文绑定时),$needsContextualBuild 为真。
如果您希望无参数 resolve 始终解析最后解析的实例,您可以执行以下操作:
//Bind or singleton doesn't matter now
$this->app->bind('blah', function ($app, $options) {
return $app->makeWith(Something::class, $options);
});
$this->app->afterResolving('blah', function ($resolvedObject) {
$this->app->instance('blah', $resolvedObject);
});
$this->app->makeWith('blah', [ 'a' => 'b' ]); //New object 1
$this->app->make('blah'); //Reused object 1
$this->app->makeWith('blah', [ 'a' => 'b' ]); //New object 2
$this->app->make('blah'); //Reused object 2
请注意,用不同的上下文解析相同的别名仍然会解析一个新对象并将该对象绑定为'blah' 的默认实例。