PHP CURLOPT_PROGRESSFUNCTION为函数添加额外的自定义参数

时间:2013-01-11 20:59:57

标签: php curl

我想知道是否可以在使用

时调用的函数中添加自定义参数
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array($this, 'progressFunction'));

所以函数签名看起来像

private function progressFunction($clientp, $dltotal, $dlnow, $ultotal, $ulnow, $myCustomParameter) { }

而不是

private function progressFunction($clientp, $dltotal, $dlnow, $ultotal, $ulnow) { }

感谢。

2 个答案:

答案 0 :(得分:10)

好的,这是一个严格的建议,我会把它作为答案,因为我认为它可能有用;

Php支持匿名函数,因此您可以像这样传递它:

curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($clientp, $dltotal, $dlnow, $ultotal, $ulnow) {

});

现在的诀窍是使用use传递您的参数,所以:

curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function (...) use ($myCustomParameter) {
    // Your code
    });

答案 1 :(得分:0)

在PHP类中,您可以将其他参数(如$statusName)传递给另一个函数,如下所示:

curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($resource, $downloadSize, $downloaded, $uploadSize, $uploaded) use ($statusName) {
    $this->progress($resource, $downloadSize, $downloaded, $uploadSize, $uploaded, $statusName);
});

然后,您的专用进度功能甚至不会使代码更加复杂:

private function progress($resource, $downloadSize, $downloaded, $uploadSize, $uploaded, $statusName="curl_download_status")
{
    // emit the progress    
    Cache::put($statusName, [
        'resource' => $resource,
        'download_size' => $downloadSize,
        'downloaded' => $downloaded,
        'upload_size' => $uploadSize,
        'uploaded' => $uploaded
    ], 10);

}