对象常量的可见性
我发现 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个相当哲学的问题,在 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.
好吧,常量是静态定义,绑定到类,而不是实例化的对象。它们只能使用
classname::constname
来寻址,并且不能改变。按理说它们是类蓝图的一部分,因此对它们应用可见性规则并没有真正的意义。不过,这只是我相当主观的意见。有兴趣看看是否有任何基于硬 OOP 理论的东西出现。
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.