我在 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 。我收到此错误:
undefined variable :userId
。
为什么会这样?该变量在内部函数的范围内声明。我唯一的想法是,它是一个回调函数。
当我尝试执行这个函数时:$obj = $user->whereHas('tournaments', function($query, $tourId){...}
然后我得到这个异常:
Missing argument 2 for User::{closure}()
最佳答案
您的 $tourId
变量不在您的匿名函数的范围内。查看 use
关键字,了解如何将它添加到作用域中。请参阅本页上的示例 3:http://www.php.net//manual/en/functions.anonymous.php
它应该看起来像下面这样:
$obj = $user->whereHas('tournaments', function($query) use($tourId)
{
var_dump($tourId); // Dumps OK
})->get();
关于回调函数中变量的PHP错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24223325/