如何解决从闭包内部更新全局范围内的变量值
im尝试对我的数据库对象进行并行处理(things
),im使用此程序包并行运行事物
https://github.com/spatie/async
我想知道我有多少东西已成功处理,因此我在全局范围内定义了$stats
数组,并尝试从内部进行更新
$pool = Pool::create();
$things = Thing::all();
$stats = [
'total' => count($things),'success' => [],];
foreach ($things as $thing) {
$pool->add(function () use ($thing,$stats ) {
// do stuff
return [$thing,$stats] ;
})->then(function ($output ) {
// Handle success
list( $thing,$stats) = $output ;
dump('SUCCESS');
$stats['success'][$thing->id] = $thing->id ;
}) ->catch(function ($exception){
// Handle exception
dump('[ERROR] -> ' . $exception->getMessage());
});
}
$pool->wait();
dump($stats);
即使我在输出中看到成功,但是当我在末尾$stats
转储success
时始终为空
array:3 [▼
"total" => 3
"success" => []
]
我还试图通过stats
将then
传递给use
并没有任何作用
})->then(function ($output ) use ($stats)
当我将$stats
转储到then
中时,我可以看到数据运行正常
})->then(function ($output ) {
// Handle success
list( $thing,$stats) = $output ;
dump('SUCCESS');
$stats['success'][$thing->id] = $thing->id ;
dump( $stats);
})
then
内部转储的输出
array:3 [▼
"total" => 3
"success" => array:1 [▼
2 => 2
]
]
解决方法
您需要做几件事:
通过引用从父作用域继承$stats
,在第一个回调中使用以下内容:
use ($thing,&$stats)
然后返回与引用相同的变量:
return [$thing,&$stats];
最后,在下一个回调中,也通过引用取消引用相应的$output
数组:
list($thing,&$stats) = $output; // or [$thing,&$stats] = $output;
注意:这看起来有点粗略,我不确定这是否是使用该库的正确方法,但这至少应该可以工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。