Diego Magalhães Diego Magalhães - 2 years ago 110
PHP Question

Symfony event addListener and variable Scope/State

I'm currently using sitl/curl-easy to make a multi-curl parallel requets, but I'm having some hard time with scope / state:

// Init queue of requests
$queue = new \cURL\RequestsQueue;

... init queue options

// Set function to be executed when request will be completed
$queue->addListener('complete', function (\cURL\Event $event)
$response = $event->response->getContent();

// ugly :D, get the key from the object request
$key = explode("&key=", array_values($event->request->getOptions()->toArray())[0])[1];

// if response is not null, truncate it to use less space
if ($response != null){
$response = str_replace(array("\r", "\n"), "", $response);

>>>>>>>> DON'T WORK, $banner_holder is declared on the top of the php page
array_push($banner_holder, array("key"=> $key,"content"=>$response));

How to push the array of $key and $response outside the listener?

Thanks in advance.

Answer Source

Since you are using a closure function you will need to specify that you want to "use" the $banner_holder array like so

$queue->addListener('complete', function (\cURL\Event $event) use ($banner_holder) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download