Dummy php closure scope problem

I was php-hacking a project using sitl/curl-easy to make a multi-curl parallel requets, but I was having some hard time with scope / state:

// Init queue of requests
$queue = new cURLRequestsQueue;
... init queue options

// Set function to be executed when request will be completed
$queue->addListener('complete', function (cURLEvent $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?

Ohhh well, it was just simple as adding use ($banner_holder) in the closure code:

$queue->addListener('complete', function (cURLEvent $event) use ($banner_holder) 

I’ll keep that wrote down here in the case of later needing 😉

Leave A Comment

Your email address will not be published. Required fields are marked *