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

后端 未结 6 914
逝去的感伤
逝去的感伤 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: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
    

提交回复
热议问题