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

后端 未结 6 1291
执笔经年
执笔经年 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:41

    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
    

提交回复
热议问题