[英]Paramaters to anonymous functions in php
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?
我不太了解$ app参数的来源以及编码器如何将其传递给匿名函数?
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. 在您的示例中,如果浏览了属于
app
对象的$this->app->singleton
方法的源代码,则会在某处找到一个函数-通常称为callback
。
$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: $app
只是访问传递给该函数的参数,您可以使用$a
或$b
或任何类似于普通用户定义函数的参数:
$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. singleton()
方法接受可调用类型的参数,该参数是字符串函数名称或匿名函数。
The singleton()
method will pass something to this function that the function can use as $app
in your example or $variable
above. singleton()
方法将向此函数传递一些信息,该函数可以在您的示例中用作$app
或上面的$variable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.