我使用以下代码与Guzzle for PHP进行并发请求:
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$client = new Client();
$myvar = 12345;
$requests = function ($total) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$pool = new Pool($client, $requests(100), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
// this is delivered each successful response
var_dump($myvar);
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
如何访问&#39;中的数据?处理程序部分在函数范围之外?显示的代码显示NULL,表示无法访问$ myvar变量。
答案 0 :(得分:4)
使用
声明将为您提供帮助。< / p>&#xA;&#xA;
'履行'=&gt; function($ response,$ index)use($ myvar){&#xA; //这是每次成功回复的结果&#xA;的var_dump($ MYVAR);&#XA;}&#XA; 代码>
&#XA;