编程语言
首页 > 编程语言> > php – 带有匿名函数和闭包的cURL WRITEFUNCTION回调

php – 带有匿名函数和闭包的cURL WRITEFUNCTION回调

作者:互联网

我正在使用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()?

我最终会使用ParalellCurl和一个常见的回调函数,这就是为什么有一个匿名函数需要用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);
}

标签:php,closures,curl,anonymous-function
来源: https://codeday.me/bug/20190903/1798269.html