0
不兼容如何將下面的匿名函數轉換爲php庫中的php函數庫:php庫中的匿名函數與php 5.2
curl_setopt($curl, CURLOPT_WRITEFUNCTION, function($handle, $data) use (&$headers, &$body, &$header_length, $max_data_length) {
$body .= $data;
if ($headers == '') {
$headers_end = strpos($body, "\r\n\r\n");
if ($headers_end !== false) {
$header_length = $headers_end;
$headers = substr($body, 0, $header_length);
$body = substr($body, $header_length + 4);
# Now that we have headers, if the content type is not HTML, we do
# not need to download anything else. Prevents us from downloading
# images, videos, PDFs, etc. that won't contain redirects
# Until PHP 5.4, you can't import $this lexical variable into a closure,
# so we will need to duplicate code from contentTypeFromHeader()
# and hasHTMLContentType()
if (preg_match('/^\s*Content-Type:\s*([^\s;\n]+)/im', $headers, $matches)) {
if (stripos($matches[1], 'html') === false) { return 0; }
}
}
}
# If we have downloaded the maximum amount of content, we're done.
if (($header_length + strlen($body)) > $max_data_length) { return 0; }
return strlen($data);
});
謝謝!
謝謝,這是我的想法,但「使用」的一部分匿名函數令我感到困惑,不知道如何使用上述命名函數: function($ handle,$ data)use(&$ headers,&$ body,&$ header_length,$ max_data_length){ –
@MartinS'use' ,在PHP的lambda函數的災難性藉口中,相當於命名函數中的'global',並且可以這樣翻譯。我會更新答案以反映這一點。 –
這不等同。 'use'從其定義範圍導入變量,'global'僅限於全局範圍,因此如果要訪問存儲在這些變量中的結果,則必須在範圍內聲明它們是全局的。 –