问题
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;
}
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.
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}()
回答1:
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();
来源:https://stackoverflow.com/questions/24223325/php-error-with-variable-in-callback-function