php 中匿名函数的参数

Paramaters to anonymous functions in php

我是匿名函数世界的新手。

  $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() 方法接受类型为 callable 的参数,它是字符串函数名称或匿名函数。

singleton() 方法会将一些东西传递给此函数,该函数可以用作您示例中的 $app 或上面的 $variable

嗯,首先,您需要将匿名函数视为在另一个上下文中执行某些语句的门。

这是一种颠倒函数声明的方式-可以这么说-。

例如,这是 declare/call 函数的传统方法:

// 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-在某处打电话。