Object variable lose context in PHP pthreads

2020-04-18 05:07发布

问题:

I was working with pthreads in PHP and noticed that pthreads loses object variables in its context, is this normal or a bug or I'm doing something wrong ?

class Downloader extends Thread {

    private $ch;

    public function __construct($data) {
        $this->ch = curl_init();
    }

    public function __destruct() {
        curl_close($this->ch);
    }

    public function run() {
        // we just lost resource of curl -> [resource(4) of type (Unknown)]
        curl_setopt($this->ch, CURLOPT_URL, $this->url);
    }
}

回答1:

It's normal: https://gist.github.com/krakjoe/6437782

There is no point in me writing the relevant parts out again; you will benefit from reading the whole article.

TL;DR Resources are officially unsupported, coupled with how pthreads objects work, this leads to the behaviour you are experiencing.