我有这样的功能:
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。
答案 0 :(得分:4)
您应该允许匿名函数捕获范围之外的变量。 $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();
});
答案 1 :(得分:1)
您必须添加use($entity_id)
,因为该变量超出了需要使用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();
});