我们能设置类常量的可见性吗?
就像这个例子:
class MyClass {
const CONST_VALUE = 'A constant value';
}
我们能否指定
public const CONST_VALUE = 'A constant value';
或者private const CONST_VALUE = 'A constant value';
或者protected const CONST_VALUE = 'A constant value';
我们能设置类常量的可见性吗?
就像这个例子:
class MyClass {
const CONST_VALUE = 'A constant value';
}
我们能否指定
public const CONST_VALUE = 'A constant value';
或者private const CONST_VALUE = 'A constant value';
或者protected const CONST_VALUE = 'A constant value';
更新:PHP 7.1(于2016年12月1日发布)中添加了常量的可见性修饰符。请参见RFC:Support Class Constant Visibility。
语法如下:
class ClassName {
private const PRIVATE_CONST = 0;
protected const PROTECTED_CONST = 0;
public const PUBLIC_CONST = 0;
}
从 PHP7.1 开始,类常量允许使用可见性修饰符,在之前的版本中无法设置类常量的可见性。它们总是公共的。有关更多信息,请参见http://www.php.net/manual/en/language.oop5.constants.php中的评论。
另一种选择是使用常量方法,例如:
private static function gravitationalConstant() {
return 9.81;
}
引用自Fowler的重构书:
这个习惯用法对于基于C的程序员来说不太熟悉,但对于Smalltalkers来说非常熟悉(因为他们的语言中没有常量)。总的来说,我不倾向于在Java中使用它,因为它不符合该语言的习惯用法。然而,如果你需要用计算出的值替换简单的返回语句,那么将常量字段更改为常量方法是值得的。(我想应该有一个重构来解决这个问题....)
在 PHP 最新版本(PHP 7.1.0)中,它将可用。
示例语法如下:
class Token {
// Constants default to public
const PUBLIC_CONST = 0;
// Constants then also can have a defined visibility
private const PRIVATE_CONST = 0;
protected const PROTECTED_CONST = 0;
public const PUBLIC_CONST_TWO = 0;
//Constants can only have one visibility declaration list
private const FOO = 1, BAR = 2;
}
在 PHP 中,常量不允许使用修饰符。 您可以使用
public static $variable = "abc";
但可悲的是,这里不允许使用 final
。