我有这样一个函数:
public function entity($entity_id, Request $request)
{
$expiresAt = Carbon::now()->addMinutes(10);
$entity = Cache::remember('entities', $expiresAt, function () {
return Entity::where('id', $entity_id)
->with('address')
->with('_geoloc')
->first();
});
然而,这会返回一个错误,指出 $entity_id 未定义,但是当我在 $expiresAt 之后执行 dd($entity_id) 时,它在我取回 id 时被定义,如果需要,id 来自 url。
最佳答案
您应该允许匿名函数捕获作用域外的变量。 $entity_id
它在范围之外。这就是 php 表达闭包的方式。使用 use()
会起作用。
public function entity($entity_id, Request $request)
{
$expiresAt = Carbon::now()->addMinutes(10);
$entity = Cache::remember('entities', $expiresAt, function () use($entity_id) {
return Entity::where('id', $entity_id)
->with('address')
->with('_geoloc')
->first();
});
关于php - Laravel Cache,闭包内的变量未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912152/