php中匿名函数的参数
我不熟悉匿名函数的世界php中匿名函数的参数,php,anonymous-function,Php,Anonymous Function,我不熟悉匿名函数的世界 $this->app->singleton(VideoServiceInterface::class, function($app) { statement1; statement2; ......... }); 我在某处偶然发现了上面的代码片段。我真的不明白$app参数从何而来,以及编码器是如何将其传递给匿名函数的?$app只是一个参数,用于访问传递给函数的内容,您可以使用$a或$b或其他类似于普通
$this->app->singleton(VideoServiceInterface::class, function($app) {
statement1;
statement2;
.........
});
我在某处偶然发现了上面的代码片段。我真的不明白$app参数从何而来,以及编码器是如何将其传递给匿名函数的?$app只是一个参数,用于访问传递给函数的内容,您可以使用$a或$b或其他类似于普通用户定义函数的功能:
$this->app->singleton(VideoServiceInterface::class, function($variable) {
//do something with $variable
});
singleton方法接受类型为字符串函数名或匿名函数的参数
singleton方法将向该函数传递一些内容,该函数可以在您的示例中用作$app或上面的$variable。首先,您需要将匿名函数视为在另一个上下文中执行某些语句的门 可以说,这是一种反转函数声明的方法 例如,以下是声明/调用函数的传统方法:
// 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方法的源代码,您会发现一个函数(通常称为回调函数)在某个地方调用