I have the class below, in order to analyze a URL
<?php
class URLFetcher {
private $ch;
private $url = '';
public function __construct(string $url) {
$this->url = $url;
}
public function fetch(): URLFetcher {
$headers = [];
$this->ch = curl_init($this->url);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',
CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$headers) {
var_dump($header);
$header2 = trim($header);
if($header2 !== '') $headers[] = $header2;
return strlen($header);
}
]);
exit(var_dump($headers));
return $this;
}
}
?>
I use var_dump in the closure in order to see the headers, as they come from CURL, and at the end, I use var_dump again in order to see all headers.
The problem is that there are no headers printed in the function and at the end, the $headers is printing the empty array.
If I do this without the class, everything works correctly. My question is what am I missing and the code does not work? I hypothesize that it has to do with the closure.