Difference between `instance` vs `bind` ?
What is the difference between instance vs bind in container ?
I believe both bind some instance to a another thing...
app()->instance('a', 2);
app()->bind('a', fn() => 2);
dd(app('a')); //2
TL;DR;
- use
->bind()when you want to provide just a FQCN (full-qualified class name), or a factory closure, to instruct the container on how to lazily build an instance only when needed. - use
->instance()when you already have an constructed instance and want to instruct the container to provide that particular instance when required.
->instance() and ->singleton() are similar on practice. The difference being that with ->singleton() you can provide a FQCN or a factory closure so the container can lazily build the instance only when needed. But on both cases the container will hold and provide the same instance every time it is required.
Simple Bindings
We can register a binding using the bind method, passing the class or interface name that we wish to register along with a closure that returns an instance of the class
reference: https://laravel.com/docs/9.x/container#simple-bindings
Binding Instances
You may also bind an existing object instance into the container using the instance method. The given instance will always be returned on subsequent calls into the container
reference: https://laravel.com/docs/9.x/container#binding-instances
Please or to participate in this conversation.