亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從閉包內部更新全局范圍內的變量值

從閉包內部更新全局范圍內的變量值

PHP
藍山帝景 2023-11-04 21:00:41
我試圖并行地對我的數據庫對象執行一些處理(things),我使用這個包并行運行事物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);    })內部轉儲的輸出thenarray:3 [▼  "total" => 3  "success" => array:1 [▼    2 => 2  ]]
查看完整描述

1 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

您需要做幾件事:

$stats通過引用從父作用域繼承,在第一個回調上使用以下內容:

use ($thing, &$stats)

然后返回相同的變量作為引用:

return [$thing, &$stats];

最后,$output在下一個回調中也通過引用取消引用相應的數組:

list($thing, &$stats) = $output;  // or [$thing, &$stats] = $output;

注意:這看起來有點粗略,我不確定這是使用這個庫的正確方法,但這至少應該有效。


查看完整回答
反對 回復 2023-11-04
  • 1 回答
  • 0 關注
  • 152 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號