php - can't access global variables from Threa

2019-08-15 18:18发布

问题:

I suppose this is a specific question, but for some reason, when I create a Thread like this:

require_once(__DIR__.'/myotherfile.php');
class StreamBufferInput extends Thread {
    public function run(){
            global $max_buffer_size;
            global $data_source;    
            echo "DATA:" . $max_buffer_size;
            ...
    }
}

myotherfile.php has those two variables declared in it (and they can be accessed from other classes, but my echo statement here prints DATA: and nothing else. I couldn't find much on doing global variables within classes, but I have a global declaration like this in a function of one of my other classes, and it works fine.

EDIT: Here is how I'm starting the Thread.

$stream = new StreamBufferInput();
$stream->start();

回答1:

This is not possible in PHP at the moment. You cannot access global scope variables defined outside a thread from within the thread itself. However, you can execute a callable from within the thread, in the global scope by using Thread::globally, I believe this could help you achieve what you want.

You can read some more about this here