为什么 PHP 不允许私有常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6770407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:12:19  来源:igfitidea点击:

Why doesn't PHP permit private const?

phpoopconstprivateencapsulation

提问by leo

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?

我有一个类在其内部实现中受益于常量的使用,但我想限制这些常量的可见性。为什么 PHP 不允许私有常量?是否有另一种方法可以实现这一目标,或者 PHP 是否试图阻止我不知道的某种类型的设计失误?

采纳答案by sudhir chauhan

Use private staticproperties.

使用private static属性。

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.

在这种情况下,您将在所有对象中拥有相同的变量,如果您想将其范围扩展到嵌套,您可以公开一个 getter 方法来获取其值并限制变量设置。

回答by Jeroen De Dauw

As of PHP 7.1, there are real private constants.

从 PHP 7.1 开始,有真正的私有常量。

private const PRIVATE_CONST = 0;

See the Class Constant Visibility RFCfor more information.

有关更多信息,请参阅类常量可见性 RFC