Akshay Naik
Akshay Naik

Reputation: 104

Getting value of variable defined in class

public function showMatch($id){
    $bat_perfo = Cache::remember('bat_1_'.$id, 2, function(){
        return Bat::whereRaw('match_id = ? AND inning = 1', array($id))->get();
    });
    return 0;
}

I am getting the error "Undefined variable: id" on line 3

how do i solve this

Upvotes: 0

Views: 51

Answers (2)

michal.hubczyk
michal.hubczyk

Reputation: 697

Add "use" keyword

public function showMatch($id){
    $bat_perfo = Cache::remember('bat_1_'.$id, 2, function() use ($id){
        return Bat::whereRaw('match_id = ? AND inning = 1', array($id))->get();
    });
    return 0;
}

Upvotes: 1

deceze
deceze

Reputation: 522352

See Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?.

The function introduces a new scope, and $id is not in scope inside the function. Use use to extend its scope:

public function showMatch($id){
    $bat_perfo = Cache::remember('bat_1_'.$id, 2, function () use ($id) {
        return Bat::whereRaw('match_id = ? AND inning = 1', array($id))->get();
    });
    return 0;
}

Upvotes: 2

Related Questions