I have a problem with distributing a static variable between different threads in PHP. In simple words, I want 1. Write a static variable in one thread 2. Read it in another thread and follow the necessary process and clear it. To test the above requirements, I wrote a PHP script below.
<?php class ThreadDemo1 extends Thread { private $mode; //to run 2 threads in different modes private static $test; //Static variable shared between threads //Instance is created with different mode function __construct($mode) { $this->mode = $mode; } //Set the static variable using mode 'w' function w_mode() { echo 'entered mode w_mode() funcion'; echo "<br />"; //Set shared variable to 0 from initial 100 self::$test = 100; echo "Value of static variable : ".self::$test; echo "<br />"; echo "<br />"; //sleep for a while sleep(1); } //Read the staic vaiable set in mode 'W' function r_mode() { echo 'entered mode r_mode() function'; echo "<br />"; //printing the staic variable set in W mode echo "Value of static variable : ".self::$test; echo "<br />"; echo "<br />"; //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 "<br />"; 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 result: Mode in the run () method: W entered mode w_mode () funcion Static variable value: 100
The mode in the run () method: R the entered r_mode () mode The value of the static variable: 100
The mode in the run () method: R the entered r_mode () mode The value of the static variable: 100
But in fact, I get the output like, Mode in the run () method: W entered mode w_mode () funcion Static variable value: 100
The mode in the run () method: R the entered mode r_mode () The value of the static variable:
The mode in the run () method: R the entered mode r_mode () The value of the static variable:
.... Really does not realize the reason. Please, help.
source share