PHP与其他语言中的静态变量等效吗?

问题描述:

我想知道PHP在类中是否具有某种类型的变量,其功能类似于其他语言中的static.我的意思是,同一类的所有对象都使用相同的变量,并且当它在一个变量上更新时,它在每个变量上都更新.静态接近,因为它在所有对象*享,但是我需要能够对其进行更新.我需要为此使用全局变量吗?

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 when it's updated on one it's updated on every one. Static is close because it is shared throughout all objects but I need to be able to update it. Will I have to use globals for this?

我认为static是您想要的.您可以更新静态变量,只需在静态上下文"中进行操作即可(即,使用::运算符.

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());

将输出:

int 0

int 1