PHP error with variable in callback function

2020-04-16 17:37发布

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条回答
闹够了就滚
2楼-- · 2020-04-16 18:04

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();
查看更多
登录 后发表回答