Why are anonymous functions used in ioc containers like Pimple

I know in Pimple container, dependencies are declared as

$container = new Pimple(); 
$container['db'] = function (){
  return new SomeClass; 
}; 

      

My question is what if I just declared dependencies as simple arrays like this.

$container = new Pimple();
$container['db'] = new SomeClass; 

      

What is the difference?

+3


source to share


1 answer


The difference is lazy loading , in particular lazy initialization .

Your first example SomeClass

is not actually instantiated until it is requested. In the second example, it is immediately created. Thus, even if the query never hits the database, the object is created and the connection is established.



Using your first example, the connection to the database is never established if the query never uses the database.

+4


source







All Articles