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

Void's avatar
Level 1

bind vs singleton: when and what to choose?

Hello. How can I know when I need to use "bind" and when to make "singleton"?

0 likes
8 replies
adamprickett's avatar
Level 6

Use bind for reusable classes or objects - the object is constructed each time it is called. If you need multiple instances of a class, use bind

Use singleton for a class or object that you need access to throughout the application - the object is only constructed once and so retains state throughout execution. If you only need a single, shared, instance of a class, use singleton

For example:

app\Support\TestClass.php

<?php

namespace App\Support;

class TestClass
{
    protected $value = 0;

    public function increase()
    {
        $this->value++;

    return $this->value;
    }
}

AppServiceProvider.php

...
public function register()
{
    $this->app->singleton(
        'test1',
        \App\Support\TestClass::class
    );

    $this->app->bind(
        'test2',
        \App\Support\TestClass::class
    );
}
...

Tinker:

>>> app('test1')->increase()
=> 1
>>> app('test1')->increase()
=> 2
>>> app('test1')->increase()
=> 3

>>> app('test2')->increase()
=> 1
>>> app('test2')->increase()
=> 1
>>> app('test2')->increase()
=> 1
52 likes
Void's avatar
Level 1

Now I get it. Finally! Thanks a lot!

hendra1's avatar

So can I say that bind always creates a new instance?

sietzekeuning's avatar

yes, exactly. You could echo something in the __construct function and see that is does echo every time if you use 'bind' and only echo once if you use 'singelton'

ollieread's avatar

No, that is not the case. The bind function has a third parameter, shared that has a default value of false. Passing true to this would have the same effect as singleton because that actually just proxies a call to bind.

1 like
ollieread's avatar

While the answer from @adamprickett is technically correct, it is omitting some details.

There is a single way to bind to Laravels container and that is using the Application::bind() method. There are however, a bunch of helper methods such as singleton(), singletonIf(), etc, etc, all of which proxy to bind().

The Application::bind() method has the following signature.

public function bind($abstract, $concrete = null, $shared = false)

Here is the singleton() method.

public function singleton($abstract, $concrete = null)
{
    $this->bind($abstract, $concrete, true);
}

So to be more specific, the difference is between shared and non-shared bindings, rather than the usage of bind() or singleton().

8 likes

Please or to participate in this conversation.