Prz*_*tas 2 php laravel laravel-5
我有一个这样的功能:
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();
});
Run Code Online (Sandbox Code Playgroud)
然而,这会返回一个错误,说 $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();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
643 次 |
| 最近记录: |