Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

untymage's avatar

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
0 likes
6 replies
untymage's avatar

@tisuchi i didnt talk about singleton, it's about "instance" method vs "bind" method

rodrigo.pedra's avatar
Level 56

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

5 likes
rodrigo.pedra's avatar

based on your example try this:

app()->bind('a', fn() => 2);
app()->instance('b', fn() => 2);


dd(app('a'), app('b'));

app('a') will return 2 just as before.

But app('b') will return a reference to the the closure, because app()->instance(...) assumes the value is already built and you, the developer, only wants the container to hold the value without trying to do anything with it.

3 likes

Please or to participate in this conversation.