异步变量作用域 PHP (Guzzle)
Variable Scope with Async PHP (Guzzle)
我正在尝试使用 Guzzle 异步请求根据 api 响应填充对象的属性。
我如何在要操作的响应处理程序中访问像下面的 $myObj
这样的对象?
原样,$myObj
无法访问。我确实发现在 class 中工作时,可以从响应处理程序中访问 $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) {
}
};
您可以尝试将 $myObj 设为全局。例如,在行上方添加行:global $myObj;
:$data = json_decode($res->getBody());
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
},
我正在尝试使用 Guzzle 异步请求根据 api 响应填充对象的属性。
我如何在要操作的响应处理程序中访问像下面的 $myObj
这样的对象?
原样,$myObj
无法访问。我确实发现在 class 中工作时,可以从响应处理程序中访问 $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) {
}
};
您可以尝试将 $myObj 设为全局。例如,在行上方添加行:global $myObj;
:$data = json_decode($res->getBody());
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
},