PHP: Sharing a static variable between threads

I have a problem in sharing static variable between different threads in PHP.
In simple words I want to

  1. Write a static variable in one thread
  2. Read it in other thread and do the required process and clean it.
    For testing above requirement I have written below PHP script.
<?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 "
"; //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.

Your static variable can’t be private if you want to share it between classes.

[php]<?php

class MyParent {

protected static $test;

public function main() {
    self::$test = 3;
    echo (self::$test) . '<br>';
}

}

class Child1 extends MyParent {

function set() {

    self::$test = 2;
}

}

class Child2 extends MyParent {

function show() {

    echo(self::$test);
}

}

$main = new MyParent();
$main->main(); // prints 3
$c1 = new Child1();
$c1->set();
$c2 = new Child2();
$c2->show(); // prints 2

[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service