You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Guzzle Promise的then方法中访问外部变量?

解决Guzzle异步请求闭包中无法访问外部变量的问题

问题核心是PHP的匿名函数(闭包)默认不会自动获取外部作用域的变量,必须通过use关键字显式声明要引入的变量,不用global也能解决。

你只需要修改then方法里的回调函数,把需要用到的$api、$data、$account_data、$list_id通过use引入进去,修改后的代码如下:

$data = [
    'email' => $email,
];

if (!empty($name)) {
    $data['fname'] = $name;
}

$request = $api->postAsync('v1/subscribers', [
    'auth' => [$account_data['api_key'], ''],
    'headers' => [
        'Content-Type' => 'application/json',
    ],
    'body' => json_encode([
        'first_name' => $data['fname'] ?? '',
        'email' => $data['email'],
    ]),
]);

$request->then(
    // 这里通过use引入需要的外部变量
    function (ResponseInterface $res) use ($api, $data, $account_data, $list_id) {
        $api->post('v1/subscribers/' . $data['email'] . '/segments', [
            'auth' => [$account_data['api_key'], ''],
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode([
                'segment_ids' => [$list_id],
            ]),
        ]);
    }
);

$request->wait();

补充说明

  • use默认是值传递,如果后续你需要在闭包里修改外部变量的值,可以在变量前加&(比如use (&$api)),但这里只是调用$api的方法,值传递就足够。
  • 要确保这些通过use引入的变量,在闭包执行时(也就是第一个请求完成后)仍然处于有效作用域内,没有被提前销毁。

内容的提问来源于stack exchange,提问作者fyrekcaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 21:42:46