PHP与其他语言中的静态变量等效吗? [英] What's the PHP equivalent of a static variable in other languages?

查看:60
本文介绍了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

这篇关于PHP与其他语言中的静态变量等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆