Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The return value of <code>Container::share()</code> is a function that takes one argument: the container itself. In order to call it externally, you'd have to do this:</p> <pre><code>$closure = function ($container) { var_dump($container); }; $container = new Illuminate\Container\Container(); call_user_func($container-&gt;share($closure), $container); </code></pre> <p>The reason for this is due to how service definitions work. The intended use of <code>share</code> is to wrap around a service definition.</p> <p>Like this:</p> <pre><code>$container = new Illuminate\Container\Container(); $container['foo'] = $container-&gt;share(function ($container) { return new Foo(); }); </code></pre> <p>When you access a service, like this:</p> <pre><code>var_dump($container['foo']); </code></pre> <p>It checks if the value is callable, and if it is, it will try to call it as a function. If you leave off the <code>share</code>, you will get a new <code>Foo</code> instance every time. The <code>share</code> memoizes the instance and returns the same one every time.</p> <p>To re-iterate, the <code>$container</code> argument in the function returned from <code>share</code> is there because that's how service creation works. The service definition ("factory" function that you "set" on the container) is just a function that takes a container and returns the instance of the service it is creating.</p> <p>Since <code>offsetGet()</code> it is expecting the definition to take a <code>$container</code> argument, that's what <code>share</code> returns.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload