为什么类声明的常量需要静态检索?
class foo
{
const bar;
}
要访问它,我们必须执行: self::bar;
而不是 $this->bar;
这是正确的吗?如果是这样,为什么?
class foo
{
const bar;
}
and to access it we have to do: self::bar;
and not, $this->bar;
Is this correct? If so, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是正确的。原因是常量是类绑定的,而属性是实例绑定的,因此通过引用访问它没有多大意义。无论您创建多少个实例,始终只有一个 foo::bar const。
这只是一个语言设计决定,但不可能通过引用访问 const,例如,在 Java 中,您确实可以通过引用访问静态最终属性,但通常会收到编译器警告。
Yes this is correct. The reason is that a constant is class-bound whereas a property is instance-bound so it wouldn't make much sense to access it through a reference. No matter how many instances you create there will always only be one foo::bar const.
It's just a language design decision that it's not possible to access a const through a reference though, in Java for example you can indeed access a static final property through a reference but you will usually get a compiler warning.
好吧,因为它们是常量,这意味着它们是静态的(常量和静态是同义词),而且如果它们永远不会改变,那么为每个实例都有一个就没有意义,所以每个类都有它们。静态成员通过
::
访问。Well, because they are constants that means they are static (constant and static are synonyms) and also it makes no sense in having one for each instance if they don't ever change, so you have them per class. Static members are accessed with
::
.需要注意的一个好点是常量只能包含原始值,这一点迄今为止一直被忽略。它们一旦设置就无法更改,尝试在已声明的值之后设置值将导致
解析错误
。本质上,只有当类的每个实例都需要您的属性时,当然,如果需要修复它,您才应该使用常量。
A good point to note, which has been missed thus far is the fact that constants can contain only primitive values. They also cannot be changed once they are set, an attempt to set a value after its already declared will result in a
parse error
.You should essentially use constants only when your property is needed across every instance of the class, and of course if it needs to be fixed.