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

后端 未结 6 1303
执笔经年
执笔经年 2021-02-09 07:15

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:44

    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

提交回复
热议问题