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

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

<div class="post-metadata">

**Author:** ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
**Post date:** [July 11, 2019, 3:30pm 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都会清空，最后得到的还是个空数组。
