我正在使用cURL的CURLOPT_WRITEFUNCTION选项指定一个回调来处理来自cURL请求的数据。
$serverid=5;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.whatever.com');
curl_setopt(
$ch,
CURLOPT_WRITEFUNCTION,
function ($ch, $string) {
return readCallback($ch, $string, $serverid);
}
);
curl_exec($ch);
function readCallback($ch, $string, $serverid) {
echo "Server #", $serverid, " | ", $string;
return strlen($string);
}
我想使用匿名函数来调用我自己的函数,该函数确实有效(readCallback()
),这样我就可以包含与请求关联的服务器ID($serverid
)。如何正确利用闭包,以便当cURL命中我的回调匿名函数时,匿名函数知道它最初是用$serverid=5
定义的,并且可以适当地调用readCallback()
?
我最终将使用ParalellCur l和一个常见的回调来使用它,这就是为什么必须让匿名函数使用ID调用我的回调。
答案 0 :(得分:5)
如果您希望在匿名函数中访问$ serverid,则必须告诉PHP您要使用该变量。像这样:
/*
* I replaced the simple $serverid var to $serverIdHolder because
* 'use' passes the variable by value, so it won't change inside
* your anonymous function that way. But if you pass a reference
* to an object, then you are able to see always the current needed value.
*/
$serverIdHolder = new stdClass;
$serverIdHolder->id = 5;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.whatever.com');
curl_setopt(
$ch,
CURLOPT_WRITEFUNCTION,
function ($ch, $string) use ($serverIdHolder) {
return readCallback($ch, $string, $serverIdHolder->id);
}
);
curl_exec($ch);
function readCallback($ch, $string, $serverid) {
echo "Server #", $serverid, " | ", $string;
return strlen($string);
}