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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正确的答案是 PHP 中没有与 Final 等效的东西,但 static 无论如何似乎都是您想要的。
static 具有这样的属性,即它在类的所有实例中具有相同的值,因为它不依赖于特定实例。
您需要使用 :: 运算符来访问它,因为它是静态的,因此无法使用 ->。
The correct answer is that there is no equivalent in PHP to final, but static seems like what you wanted in the first place anyway.
static has the property that it will have the same value across all instances of a class, because it is not tied to a particular instance.
You will need to use the :: operator to access it, because being static, you cannot use ->.
我认为静态就是你想要的。 您可以更新静态变量,只需在“静态上下文”中执行此操作(即使用 :: 运算符。
将输出:
int 0
int 1
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.
will output:
int 0
int 1
您可以更新静态属性:
You can update static properties:
您可以简单地在 PHP 文件中创建名为 Constants 的变量。
--常量.php--
$DATABASE_NAME = "mysql"
并将该文件包含在您的文件中。 您可以更改其值。 它接近你想要的,但不好称它们为常量,因为常量并不意味着要改变,这就是让我困惑的地方:)。
You can simply create variables in a PHP file say named Constants.
--Constants.php--
$DATABASE_NAME = "mysql"
and include the file in your file. You can change its value. It comes close to what you want, but it is not good call them constants because constants aren't meant to be changed, that's what confused me :).
我认为
static
是 您正在寻找的关键字。在 PHP 中,没有什么可以阻止
static
属性被“更新”:它在第一次设置时被初始化,它在 PHP 脚本执行期间保持它的值,但你绝对可以将其设置为新值。I think
static
is the keyword you are looking for.And there is nothing that prevents a
static
property from beeing "updated", in PHP : it is initialized the first time it's set, it keeps it value during the execution of the PHP script, but you definitly can set it to a new value.我不明白为什么使变量 static 不适用于您所描述的内容(但它与关键字 Final 无关)?
I don't see why making the variable static doesn't work for what you described (but it has nothing to do with the keyword final)?