PHP类方法与闭合卷曲头

时间:2019-01-28 12:14:46

标签: php curl closures

我有下面的课程,为了分析URL

<?php
class URLFetcher {
    private $ch;
    private $url = '';

    public function __construct(string $url) {
        $this->url = $url;
    }

    public function fetch(): URLFetcher {
        $headers = [];
        $this->ch = curl_init($this->url);
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',
            CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$headers) {
                var_dump($header);
                $header2 = trim($header);
                if($header2 !== '') $headers[] = $header2;
                return strlen($header);
            }
        ]);
        exit(var_dump($headers));
        return $this;
    }
}
?>

我在闭包中使用var_dump来查看标头,因为它们来自CURL,最后,我再次使用var_dump来查看所有标头。

问题在于该函数中没有打印标题,最后$ headers正在打印空数组。

如果我这样做没有阶级,一切正常。我的问题是我缺少什么,代码不起作用?我假设它与封闭件做。

1 个答案:

答案 0 :(得分:1)

您只是在方法末尾忘记了curl_exec($this->ch);

public function fetch(): URLFetcher {
    $headers = [];
    $this->ch = curl_init($this->url);
    curl_setopt_array($this->ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',
        CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$headers) {
            $header2 = trim($header);
            if($header2 !== '') $headers[] = $header2;
            return strlen($header);
        }
    ]);

    curl_exec($this->ch);

    exit(var_dump($headers));
    return $this;
}