对象常量的可见性

发布于 2024-09-14 16:43:59 字数 194 浏览 3 评论 0原文

我发现 PHP 中的对象常量始终具有公共可见性,因此不可能将它们设置为受保护或私有,如下所示:

<?php
class MyClass {
    protected const constant = "this won't work";
}
?>

对此有何解释?我想不出强制常量公开的好理由。

I found out that object constants in PHP always have public visibility so it is not possible to set them to protected or private like this:

<?php
class MyClass {
    protected const constant = "this won't work";
}
?>

What's the explanation for this? I can't think of a good reason to force constants to be public.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

无声无音无过去 2024-09-21 16:43:59

这是一个相当哲学的问题,在 PHP 中类常量的 注释中讨论手册。争论似乎是可见性标识了谁拥有更改成员的权利,而不是谁有权阅读它们。由于常量无法更改,因此当可见性被理解为访问修饰符时,让它们支持可见性是没有意义的。如果您遵循该论点或选择问题下方的链接功能请求,则由你决定。

That's a rather philosophical question, which is discussed in the comments for Class constants in the PHP Manual. The argument seems to be that Visibility identifies who has the right to change members, not who has the right to read them. Since constants cannot be changed, there is no point in having them support visibility when visibility is understood as access modifiers. If you follow that argumentation or go with the linked feature request below your question is up to you.

我还不会笑 2024-09-21 16:43:59

我想不出强制常量公开的好理由。

好吧,常量是静态定义,绑定到,而不是实例化的对象。它们只能使用classname::constname来寻址,并且不能改变。按理说它们是类蓝图的一部分,因此对它们应用可见性规则并没有真正的意义。

不过,这只是我相当主观的意见。有兴趣看看是否有任何基于硬 OOP 理论的东西出现。

I can't think of a good reason to force constants to be public.

Well, constants are static definitions, bound to the class and not instantiated objects. They can be addressed only using classname::constname, and they cannot be altered. It stands to reason they are part of the blueprint of a class, and thus it doesn't really make sense to apply visibility rules to them.

That's just my rather subjective opinion, though. Interested to see whether anything based on hard OOP theory comes up.

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