Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a static variables value in PHP?

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

In my script I want a variable that changes true and false everytime the script is executed.

<?php
    static $bool = true;

    // Print differente messages depending on $bool
    if( $bool == true )
        echo "It's true!";
    else
        echo "It's false!";

    // Change $bools value
    if( $bool == true )
        $bool = false
    else
        $bool = true;
?>

But obviously what I'm doing is wrong. The variable $bool is constantly true and I haven't fully grasped the concept of static variables I presume. What am I doing wrong?

like image 573
Weblurk Avatar asked Feb 29 '12 10:02

Weblurk


People also ask

Can static variable value be changed?

In simple words, if you use a static keyword with a variable or a method inside a class, then for every instance that you create for that class, these static members remain constant and you can't change or modify them.

What is new static () in PHP?

New static: The static is a keyword in PHP. Static in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods.


2 Answers

PHP is not able to keep variable values between requests. This means that each time your script is called, the $bool-variable will be set to true. If you want to keep the value between requests you have to use sessions or, if you want the variable shared between sessions, some caching mechanism like APC or Memcache.

Also, static is used in PHP to declare a variable shared on the class level. It is thus used in classes, and accessed like self::$variableName; or Foo::$variableName

You can read more about static properties here. From the docs:

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

Also, note that the word static has been overloaded since PHP 5.3, and can also be used to denote Late Static Binding, by use of static::

like image 133
PatrikAkerstrand Avatar answered Oct 22 '22 20:10

PatrikAkerstrand


A static value will not persist over executions. Every time the script is executed $bool is initialized. I think you should persist this value in a file to keep it simple.

like image 2
addex03 Avatar answered Oct 22 '22 19:10

addex03