PHP 类常量 - 公共、私有还是受保护?
我假设常量属性自动公开是否正确?有没有办法将它们设为私有或受保护?
Am I correct in assuming that constant properties are automatically public? Is there a way to make them private or protected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从历史上看,只要类被加载,类常量就总是可以公开访问的,并且没有办法改变这一点。
从 PHP 7.1 开始,它们默认保持公开状态,但 现在可以应用访问修饰符。以下是发行说明中的示例:
Historically, class constants were always publicly accessible as long as the class was loaded and there was no way to change this.
As of PHP 7.1, they remain public by default but access modifiers may now be applied. Here's the example from the release notes:
类常量应该具有私有/受保护的选项,因为公开会暴露类的内部细节,其他类/代码可能会错误地使用这些细节,认为它们可以使用,因为它们是公共的。
很高兴知道更改私有常量只会影响它定义的类。不幸的是我们没有这个选项。
还记得您学习对象设计和对象设计时的情况吗?分析...您为类方法和属性提供尽可能最严格的访问限制,然后根据需要放松它们(更难返回其他方式,因为其他类/代码开始使用它们,这会破坏其他代码)。
解决方法
最好的办法是创建一个私有或受保护的变量并将其大写以表明它是一个常量。您始终可以创建一个名为 Constant($value_to_be_constant) 的类,该类实现正确的魔术方法/ spl 接口以防止其被更改。
Class constants should have the option of being private/protected because being public exposes internal details of the class that other classes/code can mistakingly use thinking they are ok to use because they are public.
It would be nice to know that changing a private constant would ONLY affect the class it's defined in. Unfortunately we don't have that option.
Remember back to when you were learning Object Design & Analysis... you give class methods and attributes the most RESTRICTIVE access possible, and later relax them as needed (much harder to go back the other way because other classes/code start using them which would then break other code).
WORKAROUND
Best bet is to just create a private or protected variable and upper-case it to show it's a constant. You could always create a class called constant($value_to_be_constant) that implements the correct magic methods / spl interfaces to prevent it from being changed.
我知道这个问题已有 6 年历史
Php 7.1(当前为 RC1)允许指定类常量的可见性。
其他信息
I am aware this question is 6 years old
Php 7.1 (currently RC1) allows to specify visibility on class constants.
Additional info
从 php7.1 开始,您可以使用访问修饰符(
public
、private
或受保护
)。看一下以下示例:鸣谢:http://dwellupper。 io/post/48/defining-class-constants-in-php
As of php7.1, you can define your class constants with access modifiers (
public
,private
orprotected
). Have a look at the following example:Credits: http://dwellupper.io/post/48/defining-class-constants-in-php