PHP错误,回调函数中有变量 [英] PHP error with variable in callback function
问题描述
我在php(laravel)中具有此功能:
I have this function in php (laravel):
public static function isUserParticipatesInTournament($tourId, $userId)
{
var_dump($userId); //dumped
$user = User::find($userId);
if(!$user)
{
return null;
}
$obj = $user->whereHas('tournaments', function($query)
{
var_dump($tourId); //error
$query->where('id', '=', $tourId); //error
})->get();
return $obj;
}
问题在于,在闭包$obj = $user->whereHas('tournaments', function($query){...}
中,未定义$tourId
变量.我收到此错误:
Undefined variable: userId
.
The problem is that in the closure $obj = $user->whereHas('tournaments', function($query){...}
the $tourId
variable is undefined in it. I am getting this error:
Undefined variable: userId
.
为什么会这样?该变量在内部函数的范围内声明.我唯一的想法是,这是一个回调函数.
Why this is happening? The variable is declared in the scope of the inner function. My only thought is that, that it is a callback function.
当我尝试执行此功能时:$obj = $user->whereHas('tournaments', function($query, $tourId){...}
,然后出现此异常:
When I tried to execute this function : $obj = $user->whereHas('tournaments', function($query, $tourId){...}
then I am getting this exception:
Missing argument 2 for User::{closure}()
推荐答案
您的$tourId
变量不在匿名函数的范围内.查看use
关键字,以了解如何将其添加到范围.请参阅此页面上的示例3: http://www.php.net//manual/zh/functions .anonymous.php
Your $tourId
variable is not in the scope of your anonymous function. Have a look at the use
keyword to see how you can add it to the scope. See example 3 on this page: http://www.php.net//manual/en/functions.anonymous.php
它应该类似于以下内容:
It should look something like the following:
$obj = $user->whereHas('tournaments', function($query) use($tourId)
{
var_dump($tourId); // Dumps OK
})->get();
这篇关于PHP错误,回调函数中有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!