Bra*_*rad 3 php curl closures anonymous-function
我正在使用CURLOPT_WRITEFUNCTION的 cURL选项指定一个回调来处理来自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);
}
Run Code Online (Sandbox Code Playgroud)
我想使用匿名函数调用我自己的函数,其中actuall确实work(readCallback()),以便我可以包含与request($serverid)相关联的服务器ID .如何正确利用闭包,以便当cURL命中我的回调匿名函数时,匿名函数知道它最初定义为$serverid=5并且可以readCallback()适当调用?
我最终将使用ParalellCur l和一个常见的回调函数,这就是为什么有一个匿名函数需要使用ID调用我的回调.
如果您希望在匿名函数中访问$ 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1555 次 |
| 最近记录: |