为什么类声明的常量需要静态检索?

发布于 2024-09-26 08:10:04 字数 157 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

大海や 2024-10-03 08:10:04

是的,这是正确的。原因是常量是类绑定的,而属性是实例绑定的,因此通过引用访问它没有多大意义。无论您创建多少个实例,始终只有一个 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.

樱娆 2024-10-03 08:10:04

好吧,因为它们是常量,这意味着它们是静态的(常量和静态是同义词),而且如果它们永远不会改变,那么为每个实例都有一个就没有意义,所以每个类都有它们。静态成员通过 :: 访问。

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 ::.

凉风有信 2024-10-03 08:10:04

需要注意的一个好点是常量只能包含原始值,这一点迄今为止一直被忽略。它们一旦设置就无法更改,尝试在已声明的值之后设置值将导致解析错误

本质上,只有当类的每个实例都需要您的属性时,当然,如果需要修复它,您才应该使用常量。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文