I have this code from a PHP course:
<?php
$ch = curl_init();
$headers = [
"Authorization: Client-ID YOUR_ACCESS_KEY"
];
$response_headers = [];
$header_callback = function($ch, $header) use (&$response_headers) {
$len = strlen($header);
$parts = explode(":", $header, 2);
if (count($parts) < 2) {
return $len;
}
$response_headers[$parts[0]] = trim($parts[1]);
return $len;
};
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.unsplash.com/photos/random",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADERFUNCTION => $header_callback
]);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $status_code, "\n";
print_r($response_headers);
echo $response, "\n";
I'm having a hard time understanding why the header_callback is written the way it is. Mostly because of the confusion provoked by the use keyword. I've been trying to understand it, but I'm not sure I did, I have a bit of a C/C background and I feel like it is something similar to variable capturing from lambda expressions in CPP.
But why do I need it in this case? Couldn't I just pass &$response_headers as a function parameter?
Thanks.
CodePudding user response:
As you are passing the function as a parameter for CURLOPT_HEADERFUNCTION
, you need to keep to the expected format of this function.
From the manual
CURLOPT_HEADERFUNCTION A callback accepting two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written by this callback. Return the number of bytes written.
So you cannot just add parameters to the function, you have to stick to the parameters passed in and the return value.
There are other instances of callback functions needing to have certain parameters (preg_replace_callback for example).