PHP-无法从线程访问全局变量? [英] php - can't access global variables from Thread?
问题描述
我想这是一个特定的问题,但是由于某种原因,当我创建这样的线程时:
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
中声明了这两个变量(可以从其他类中访问它们,但是我的echo
语句在这里显示了DATA:
,什么也没有.在类中执行全局变量方面我找不到很多东西,但是我在其他一个类的函数中有一个这样的全局声明,它可以正常工作.
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.
这是我启动线程的方式.
Here is how I'm starting the Thread.
$stream = new StreamBufferInput();
$stream->start();
推荐答案
目前在PHP中这是不可能的.您不能从线程本身内部访问在线程外部定义的全局范围变量.但是,您可以使用Thread::globally
在全局范围内的线程内从全局范围内执行可调用对象,我相信这可以帮助您实现所需的目标.
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.
您可以在此处
这篇关于PHP-无法从线程访问全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!