Reputation: 4319
I am new to the anonymous functions world.
$this->app->singleton(VideoServiceInterface::class, function($app) {
statement1;
statement2;
.........
});
I came across the above code snippet somewhere. I didn't really understand where the $app parameter came from and how did the coder pass it to the anonymous function?
Upvotes: 0
Views: 54
Reputation: 8288
well, first , you need to think about anonymous function as a gate to execute some statements in another context .
it's a kind of reversing the function declaration -so to speak-.
for instance , here is the traditional way to declare/call a function :
// Declare a function .
function foo($parameter)
{
// here we are executing some statements
}
// Calling the function
echo foo();
in the anonymous function case , we are calling the function somewhere , and moving the responsibility of declaring the function to the client user .
for example, you are writing a new package , and in a specific peace of it , you don't want to execute your package as a concrete object , giving the client user more power to declare and execute some statement to suit his needs .
function foo($parameter, $callback)
{
echo $parameter . "\n";
// here we are calling the function
// leaving the user free to declare it
// to suit his needs
$callback($parameter);
}
// here the declaration of the function
echo foo('Yello!', function ($parameter) {
echo substr($parameter, 0, 3);
});
in your example , if you browsed the source code of $this->app->singleton
method which is belongs to app
object , you will found a function -which is often called a callback
- called there somewhere.
Upvotes: 1
Reputation: 78994
$app
is just an argument to access what is passed to the function, you could use $a
or $b
or whatever just like a normal user-defined function:
$this->app->singleton(VideoServiceInterface::class, function($variable) {
//do something with $variable
});
The singleton()
method accepts an argument of type callable which is a string function name or an anonymous function.
The singleton()
method will pass something to this function that the function can use as $app
in your example or $variable
above.
Upvotes: 0