php Laravel 向函数传递了额外的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34896236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel where has passing additional arguments to function
提问by Philwn
The following obviously results in undefined variable.
以下显然会导致未定义的变量。
public function show($locale, $slug)
{
$article = Article::whereHas('translations', function ($query) {
$query->where('locale', 'en')
->where('slug', $slug);
})->first();
return $article;
}
Trying to supply the function with the $slug variable:
尝试为函数提供 $slug 变量:
public function show($locale, $slug)
{
$article = Article::whereHas('translations', function ($query, $slug) {
$query->where('locale', 'en')
->where('slug', $slug);
})->first();
return $article;
}
results in
结果是
Missing argument 2 for App\Http\Controllers\ArticlesController::App\Http\Controllers\{closure}()
how can you allow the funtion to have access to $slug? Now this is probably something simple but I cant find what i need to search for.
您如何允许该功能访问 $slug?现在这可能很简单,但我找不到我需要搜索的内容。
回答by rdiz
You have to use use
to pass variables (in your case, $slug
) into the closure (this is called variable inheriting):
您必须使用use
将变量(在您的情况下$slug
)传递到闭包中(这称为变量继承):
public function show($locale, $slug)
{
$article = Article::whereHas('translations', function ($query) use ($slug) {
$query->where('locale', 'en') // ^^^ HERE
->where('slug', $slug);
})->first();
return $article;
}
If you, in the future, want to pass $locale
in along with it, just comma-separate it:
如果您将来想$locale
与它一起传递,只需用逗号分隔它:
Article::whereHas('translations', function ($query) use ($slug, $locale) { /* ... */ });
回答by Giedrius
You need to inherit variable from parent scope:
您需要从父作用域继承变量:
public function show($locale, $slug) {
$article = Article::whereHas('translations', function ($query, $slug) use ($slug){
$query->where('locale', 'en')
->where('slug', $slug);
})->first();
return $article;
}
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
闭包也可以从父作用域继承变量。任何此类变量都必须传递给使用语言结构。