What's the PHP equivalent of a static variable in other languages?

后端 未结 6 902
逝去的感伤
逝去的感伤 2021-02-09 07:03

I\'m wondering if PHP has a type of variable in classes that functions like static in other languages. And by that I mean all objects of the same class use the same variable and

相关标签:
6条回答
  • 2021-02-09 07:32

    I think static is what you want. You can update a static variable, you just have to do it in a "static context" (ie. using the :: operator.

    class Class1 {
        protected static $_count = 0;
    
        public function incrementCount() {
            return self::$_count++;
        }
    }
    
    $instance1 = new Class1();
    $instance2 = new Class1();
    var_dump($instance1->incrementCount(), $instance2->incrementCount());
    

    will output:

    int 0

    int 1

    0 讨论(0)
  • 2021-02-09 07:35

    I don't see why making the variable static doesn't work for what you described (but it has nothing to do with the keyword final)?

    <?php
    
    class Bla
    {
        public static $var;
    
        public function __construct()
        {
            Bla::$var = Bla::$var + 1;
        }
    }
    
    $test = new Bla();
    echo Bla::$var; // 1
    $test = new Bla();
    echo Bla::$var; // 2
    
    ?>
    
    0 讨论(0)
  • 2021-02-09 07:36

    I think static is the keyword you are looking for.

    And there is nothing that prevents a static property from beeing "updated", in PHP : it is initialized the first time it's set, it keeps it value during the execution of the PHP script, but you definitly can set it to a new value.

    0 讨论(0)
  • 2021-02-09 07:40

    The correct answer is that there is no equivalent in PHP to final, but static seems like what you wanted in the first place anyway.

    static has the property that it will have the same value across all instances of a class, because it is not tied to a particular instance.

    You will need to use the :: operator to access it, because being static, you cannot use ->.

    0 讨论(0)
  • 2021-02-09 07:42

    You can update static properties:

    class A {
       protected static $_foo = 0;
    
       public function increment()
       {
           self::$_foo++;
       }   
    
       public function getFoo()
       {
           return self::$_foo;
       }
    }
    
    
    $instanceOne = new A();
    $instanceTwo = new A();
    
    
    $instanceOne->getFoo(); // returns 0
    
    $instanceTwo->increment();
    
    $instanceOne->getFoo(); // returns 1
    
    0 讨论(0)
  • 2021-02-09 07:58

    You can simply create variables in a PHP file say named Constants.

    --Constants.php-- $DATABASE_NAME = "mysql"

    and include the file in your file. You can change its value. It comes close to what you want, but it is not good call them constants because constants aren't meant to be changed, that's what confused me :).

    0 讨论(0)
提交回复
热议问题