[英]Paramaters to anonymous functions in php
我是匿名函数世界的新手。
$this->app->singleton(VideoServiceInterface::class, function($app) {
statement1;
statement2;
.........
});
我在某个地方遇到了以上代码片段。 我不太了解$ app参数的来源以及编码器如何将其传递给匿名函数?
好吧,首先,您需要考虑将匿名函数作为在另一个上下文中执行某些语句的大门。
可以说,这是一种反转函数声明的方法。
例如,这是声明/调用函数的传统方式:
// Declare a function .
function foo($parameter)
{
// here we are executing some statements
}
// Calling the function
echo foo();
在匿名函数的情况下,我们在某处调用函数,并将声明函数的职责移给客户用户。
例如,您正在编写一个新程序包,并且在特定的环境中,您不想将程序包作为一个具体对象执行,从而使客户端用户有更多的能力来声明和执行一些满足其需求的语句。
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);
});
在您的示例中,如果浏览了属于app
对象的$this->app->singleton
方法的源代码,则会在某处找到一个函数-通常称为callback
。
$app
只是访问传递给该函数的参数,您可以使用$a
或$b
或任何类似于普通用户定义函数的参数:
$this->app->singleton(VideoServiceInterface::class, function($variable) {
//do something with $variable
});
singleton()
方法接受可调用类型的参数,该参数是字符串函数名称或匿名函数。
singleton()
方法将向此函数传递一些信息,该函数可以在您的示例中用作$app
或上面的$variable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.