Laravel 匿名函数如何知道它的参数

How Laravel anonymous function know it's parameter

考虑这段代码:

$fn = FormNilai::whereHas('mataPelajaranLokalGuru',function($mlg) {
      $mlg->where('guru_id','=',$this->uid);
})->get();

$mlg 如何始终被视为 FormNilai 实例?情况如何?我阅读了很多有关依赖注入的内容,但仍然不明白这一点。

Dependency Injection 是不同的部分。根据您的代码示例,您需要告诉匿名函数使用该变量,例如...

$uid = $this->uid; 
$fn = FormNilai::whereHas('mataPelajaranLokalGuru',function($mlg) use($uid)
                    {
                        $mlg->where('guru_id','=',$uid);
                    })->get();

由于该变量 uid 在匿名函数的范围之外,因此需要使用 use 关键字将其传入,如上面的代码所示。

您可以通过示例 here

了解有关 use 的更多信息

后来我意识到 laravel 支持 php 匿名风格,所以我们可以实现这样的 javascript 函数用法,但我第一次做肯定很难

为了简单使用,他们显示了这样的示例

$users = User::with(array('posts' => function($query)
{
$query->where('title', 'like', '%first%');
}))->get();

如果用户想把第三个参数填成变量怎么办。当我用任何全局变量替换那些“%first%”字来检查它时,它破坏了结构,它发生在我身上。

$title = 'heirlom of marineford';
$users = User::with(array('posts' => function($query)
{
   $query->where('title', 'like', $title);
}))->get();

搜索 PHP 文档后,我发现通过使用 use() 扩展功能块将参数传递给该匿名函数的技术,因此该函数将假定使用由 use() 定义的所有变量) 节

$title = 'heirlom of marineford';
$users = User::with(array('posts' => function($query) use($title)
{
    $query->where('title', 'like', $title);
}))->get();

希望对你有所帮助

参数 $mlg 未被视为 FormNilai 实例,它仅被视为 Illuminate\Database\Eloquent\Builder.

的实例

你可以在源代码中看到它是如何工作的。 Illuminate/Database/Eloquent/Builder.php#L934

示例:

定义一个接受常规参数的匿名函数:

$example = function ($arg) {
    var_dump($arg);
};

$example("hello");

您可以将参数名称更改为任何字符串,就像 $myArgument.
无论参数名称是什么,输出都不会改变。