-1

I'm new to php, so I'm not sure if I can do this. I've a class which has a static variable which I'm periodically changing with the help of a static function like below. I'm reading the static variable through a getter method in another static function.

infi_file.php

class infi_file {
    private static $value = 1;

    static function run_infinite ($interval) {
        while (true) {
            print date("H:i:s") . " - " . infi_file::$value . "\n";
            sleep ($interval);
            infi_file::$value = infi_file::$value ^ 1;
        }
    }

    static function getMode () {
        return infi_file::$value;
    }
}

run_infi_file.php

require_once "infi_file.php";

infi_file::run_infinite (5);

get_value.php

require_once "infi_file.php";

print infi_file::getMode () . "\n";

So I'm running both run_infi_file.php and get_value.php files simultaeously on 2 different terminal tabs.

While the output for run_infi_file is something like this :

15:11:51 - 1
15:11:56 - 0
15:12:01 - 1
15:12:06 - 0
...

the output of get_value always seems to be 1, even when the value is changed by run_infinite function. I thought that since $value is a static variable the entire class has just one copy which's used by all functions in that class. Why is this not happening?

user3248186
  • 1,518
  • 4
  • 21
  • 34
  • 1
    are you sure that `infi_file::$value = infi_file::$value ^ 1;` is correct syntax? `$var = $var ^ 1` works like `$var++`? – Patrick Manser Mar 21 '17 at 10:12
  • yea, i guess it's bitwise xor, which is what i'm looking for – user3248186 Mar 21 '17 at 10:14
  • Create a singleton-patter for your infi_file-class. http://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5 – Oliver Mar 21 '17 at 10:17
  • created a singleton pattern as you mentioned, still no change. – user3248186 Mar 21 '17 at 11:12
  • as per @PatrickManser 's comment, if bitwise xor is what you are looking for, you are getting what you are looking for. 1^1 => 0, and 0^1 => 1. This is not about 'static variable access'. Change your ^ to a + – YvesLeBorg Mar 21 '17 at 12:19
  • yea, the problem is with the 2nd output - get_value.php - it's always printing 1, irrespective of the values printed by run_infi_file.php – user3248186 Mar 21 '17 at 12:22

2 Answers2

0

You should use self for referring to static vars inside the class

    static function getMode () {
    return self::$value;
}
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

A static function will not know of the other static methods and how they have affected variables AFAIK.

Ryan Hipkiss
  • 648
  • 1
  • 7
  • 20