为什么 PHP 不允许私有 const?
我有一个类受益于在其内部实现中使用常量,但我想限制这些常量的可见性.为什么 PHP 不允许私有常量?是否有其他方法可以实现这一点,或者 PHP 是否试图阻止我不知道的某种设计失误?
I have a class that benefits from the use of constants in its internal implementation, but I would like to limit visibility of these constants. Why doesn't PHP permit private constants? Is there another way to achieve this or is PHP trying to discourage some type of design misstep I am ignorant of?
推荐答案
使用 private static
属性.
在这种情况下,您将在所有对象中拥有相同的变量,如果您想将其范围扩展到嵌套,您可以公开一个 getter 方法来获取其值并限制变量设置.
In that case you will have the same variable throughout all objects and if you want to extend its scope to nested, you can expose a getter method to get its value and restrict variables settings.
相关文章