1

I'm trying to use Guzzle async requests to populate an object's properties based on an api response.

How would I access an object like $myObj below, inside the response handler to operate on?

As is, $myObj is not reachable. I did find when working inside a class, $this is accessible from within the response handler, but I'm hoping there's another way.

$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) {

  }
};
Coder1
  • 13,139
  • 15
  • 59
  • 89

2 Answers2

5

PHP doesn't import variable in a function context by default. You should use use to explicitly list variables that you want to import.

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
},
Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22
-2

You can try to make the $myObj global. For example add the line: global $myObj; above the line: $data = json_decode($res->getBody());

Nadir Latif
  • 3,690
  • 1
  • 15
  • 24