获取在类中定义的变量的值

时间:2014-03-17 10:21:33

标签: php laravel

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;
}

我在第3行收到错误“Undefined variable:id”

我该如何解决这个问题

2 个答案:

答案 0 :(得分:2)

请参阅Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

function引入了新范围,$id不在函数范围内。使用use扩展其范围:

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;
}

答案 1 :(得分:1)

添加"使用"关键字

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;
}