2017-01-11 5 views
1

저는 Guzzle 비동기 요청을 사용하여 API 응답을 기반으로 객체의 속성을 채우려고합니다.Async PHP (Guzzle)의 가변 범위

아래의 $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) { 

    } 
}; 
+0

가능한 복제 (http://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions) – Devon

답변

3

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 
}, 
[익명 함수에 PHP 변수]의
-2

$ myObj를 전역으로 만들 수 있습니다. 예를 들어, 라인 위에 global $myObj; 줄을 추가하십시오. $data = json_decode($res->getBody());