调用fn时未定义的变量


Undefined variable when calling fn

我在的Laravel中有一个非常简单的函数

public function getImage($slug){
    // This return an error
    $cached = Cache::remember('Test', 10, function(){
        $images = $this->allImages();
        // Undefined var $slug
        return file_get_contents($images[$slug]['image-url']);
    });
    // This works
    // $images = $this->allImages();
    // $cached = file_get_contents($images[$slug]['image-url']);
    $headers = [
        'Content-Type'      =>  'image/jpeg',
        'Cache-Control'     =>  'max-age=600'
    ];
    return Response::make($cached, 200, $headers);
}

这可能是一个愚蠢的问题,但我已经很长时间没有使用PHP了,并且回避了为什么$slug是未定义的??

当您创建一个匿名函数/闭包,稍后将其传递给Cache::remember()时,您需要明确列出父作用域中应该在该函数作用域中可用的所有变量。

use语句用于此-以下代码应该可以工作:

$cached = Cache::remember('Test', 10, function() use($slug) {
    $images = $this->allImages();
    // Undefined var $slug
    return file_get_contents($images[$slug]['image-url']);
});