I have a problem in sharing static variable between different threads in PHP.
In simple words I want to
- Write a static variable in one thread
- Read it in other thread and do the required process and clean it.
For testing above requirement I have written below PHP script.
"; //Set shared variable to 0 from initial 100 self::$test = 0; echo "Value of static variable : ".self::$test; echo "
"; echo "
"; //sleep for a while sleep(1); } //Read the staic vaiable set in mode 'W' function r_mode() { echo 'entered mode r_mode() function'; echo "
"; //printing the staic variable set in W mode echo "Value of static variable : ".self::$test; echo "
"; echo "
"; //Sleep for a while sleep(2); } //Start the thread in different modes public function run() { //Print the mode for reference echo "Mode in run() method: ".$this->mode; echo "
"; switch ($this->mode) { case 'W': $this->w_mode(); break; case 'R': $this->r_mode(); break; default: echo "Invalid option"; } } } $trd1 = new ThreadDemo1('W'); $trd2 = new ThreadDemo1('R'); $trd3 = new ThreadDemo1('R'); $trd1->start(); $trd2->start(); $trd3->start(); ?>
Expected output is,
Mode in run() method: W
entered mode w_mode()
funcion Value of static variable : 100
Mode in run() method: R
entered mode r_mode()
function Value of static variable : 100
Mode in run() method: R
entered mode r_mode()
function Value of static variable : 100
But actually I am getting the output as,
Mode in run() method: W
entered mode w_mode()
funcion Value of static variable : 100
Mode in run() method: R
entered mode r_mode()
function Value of static variable :
Mode in run() method: R
entered mode r_mode()
function Value of static variable :
…Really unaware of the cause. Please help.