As all we know the singleton concept is very useful for us. But some of the underlying concept makes me scratch my head.
say we bind one object as singleton in the following way.
$this->app->singleton(Singleton::class, function () {
return new Singleton();
});
now as we know the object will only be resolved once and then it will be saved in the container's instances class property and return in the following way
if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
return $this->instances[$abstract];
}
okay everything fine till now.now we are modifying the instance from a controller
function index(){
$abc = app(Singleton::class);
$abc->a = 'b;
}
and we are accessing the singleton on other function
function test(){
echo app(Singleton::class)->a;
}
and of course we can see it prints 'b'. But actually what we are doing in index function is saving the singleton to a variable $abc and we are modifying that variable in which I suppose reside a copy of the singleton object from the container's singleton array since laravel just return a value from its container instances array with index matches to the class name.
but how laravel manage it to reflect the change on next function when we are resolving the singleton object as above change only affects the $abc variable.
I am sure the answer could make me laugh as I am sure I have missed something in my way of thinking.
No, object instances are passed by reference.
app(Singleton::class)
does not create a copy, it always returns (a reference to) the one and only instance of Singleton::class
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With