How to change the value of static variables in PHP?

This is a simplified version of what I want to accomplish:

In my script, I need a variable that changes true and false every time the script runs.

<?php static $bool = true; // Print differente messages depending on $bool if( $bool == true ) echo "It true!"; else echo "It false!"; // Change $bools value if( $bool == true ) $bool = false else $bool = true; ?> 

But it’s obvious what I am doing wrong. The $bool variable is constantly true , and I did not fully understand the concept of static variables that I assume. What am I doing wrong?

+7
source share
3 answers

PHP cannot save variable values ​​between requests. This means that every time you call the script, $bool -variable will be set to true. If you want to keep the value between requests, you must use sessions or, if you want the variable to be shared between sessions, some APC or Memcache caching mechanism.

In addition, static used in PHP to declare a variable shared at the class level. Thus, it is used in classes and is available as self::$variableName; or Foo::$variableName

Read more about static properties here . From the docs:

Declaring class properties or methods as static makes them available without having to instantiate the class. A property declared as static cannot be accessed using an instance of a class object (although a static method can be used).

Also note that the word static was overloaded with PHP 5.3, and can also be used to denote Late Static Binding , by using static::

+14
source

Static value will not be saved at runtime. Each time a script is executed, $ bool is initialized. I think you should save this value in a file so that it is simple.

+2
source

I think you need to better understand the point of a static variable. The storage for the variable is allocated (and freed) in the call stack, so from the point of view of software development, its value cannot be changed at run time.

For this, there are better solutions proposed above.

+2
source

All Articles