带有异步 PHP 的变量范围 (Guzzle)

Cod*_*er1 1 php guzzle guzzle6

我正在尝试使用 Guzzle 异步请求根据 api 响应填充对象的属性。

我将如何访问$myObj如下所示的对象,在响应处理程序中对其进行操作?

$myObj原样无法访问。我确实发现在课堂内工作时,$this可以从响应处理程序中访问,但我希望有另一种方式。

$myObj;

$promise = $this->client->requestAsync('GET', 'http://example.com/api/someservice');
$promise->then(
  function (ResponseInterface $res) {
    $data = json_decode($res->getBody());

    // How can I access vars like $myObj from here?
    $myObj->setName($data->name);
    // ... then persist to db
  },
  function (RequestException $e) {

  }
};
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 5

默认情况下,PHP 不会在函数上下文中导入变量。您应该使用use显式列出要导入的变量。

function (ResponseInterface $res) use ($myObj) {
    $data = json_decode($res->getBody());

    // How can I access vars like $myObj from here?
    $myObj->setName($data->name);
    // ... then persist to db
},
Run Code Online (Sandbox Code Playgroud)