传递rememberForever的回调时未定义的变量错误:Laravel 5.1

时间:2015-12-18 13:13:20

标签: php laravel-5 laravel-5.1

我在做什么?

我将CategoryID参数值作为默认值传递给where子句

public function SubCategories($CategoryID)
{
    $CandSubCat = \Cache::rememberForever('CandSubCat' . $CategoryID, function() {
        return \App\Models\Skill\Category_Model
            ::where("CategoryID", "=", $CategoryID)
            ->with("SubCategories")
            ->first();
    });

    return view("Skill.SubCategory.List", array("CandSubCat" => $CandSubCat));
}

问题:

为什么它会给运行时错误,说:

  

未定义的变量:Where子句中的CategoryID?

1 个答案:

答案 0 :(得分:2)

您应该使用use关键字将变量传递到函数范围,如下所示:

public function SubCategories($CategoryID)
{
    $CandSubCat = \Cache::rememberForever('CandSubCat' . $CategoryID, function() use($CategoryID) {
        return \App\Models\Skill\Category_Model
            ::where("CategoryID", "=", $CategoryID)
            ->with("SubCategories")
            ->first();
    });

    return view("Skill.SubCategory.List", array("CandSubCat" => $CandSubCat));
}