How does the laravel singleton pattern mange reflect changes on subsequent calls?

As we know, the singleton concept is very useful to us. But some of the fundamental concepts make me scratch my head.

let's say we bind one object as a singleton as follows.

$this->app->singleton(Singleton::class, function () { return new Singleton(); }); 

now, since we know that the object will be resolved only once, and then it will be stored in the class property of the container instance and will be returned as follows.

 if (isset($this->instances[$abstract]) && ! $needsContextualBuild) { return $this->instances[$abstract]; } 

Everything is still fine. Now we modify the instance from the controller

 function index(){ $abc = app(Singleton::class); $abc->a = 'b; } 

and we turn to singleton for another function

 function test(){ echo app(Singleton::class)->a; } 

and of course we see that it prints "b". But in fact, what we do in the index function is to save a single element into the $ abc variable, and we modify this variable, which, I believe, contains a copy of the singleton object from the singleton array of the container, since laravel simply returns the value from its instances of the container, the array with the index corresponds to the class name.

but how laravel controls it to reflect the change in the next function when resolving a singleton object, as mentioned above, only affects the $ abc variable.

I am sure that the answer can make me laugh, because I am sure that I have missed something in my way of thinking.

+5
source share
1 answer

No, instances of the object are passed by reference .

app(Singleton::class) does not create a copy, it always returns (a link to) a single instance of Singleton::class .

+2
source

Source: https://habr.com/ru/post/1275696/


All Articles