# PHP在匿名函数中修改函数外部的变量

**URL:** <https://www.shiqidu.com/t/topic/596>\
**Category:** 开发调优\
**Tags:** PHP\
**Created:** [2019 年7 月 11 日 15:30 UTC](https://www.shiqidu.com/t/topic/596 "2019-07-11T15:30:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Eureka](https://www.shiqidu.com/user_avatar/www.shiqidu.com/eureka/32/5_2.png) [@Eureka](https://www.shiqidu.com/u/Eureka)\
发布日期： [2019 年7 月 11 日 15:30 UTC](https://www.shiqidu.com/t/topic/596/1 "2019-07-11T15:30:32Z")

</div>

在匿名函数中要想使用并修改外部的变量，需要使用`use(&$变量名)`，如下

```php
$planIdList = [];
$list = Report::getList($bdate, '*', $where)->each(function ($item, $key) use (&$planIdList) {
    array_push($planIdList, $item->plan_id);
    return $item;
});

```

如果不加`use`，会直接报错，因为`$planIdList`不存在，如果不加`&`，每次遍历$planidList都会清空，最后得到的还是个空数组。
