[英]php class constant visibility
Can we set visibility of class constant? 我们可以设置类常量的可见性吗?
For this example: 对于这个例子:
class MyClass {
const CONST_VALUE = 'A constant value';
}
Can we specify 我们可以指定吗?
public const CONST_VALUE = 'A constant value';
or 要么
private const CONST_VALUE = 'A constant value';
or 要么
protected const CONST_VALUE = 'A constant value';
Update: visibility modifiers for constants have been added in PHP 7.1 (released 1st of December 2016). 更新:常量的可见性修饰符已添加到PHP 7.1(2016年12月1日发布)中。 See the RFC : Support Class Constant Visibility .
请参阅RFC: 支持类常量可见性 。
The syntax looks like this: 语法如下所示:
class ClassName {
private const PRIVATE_CONST = 0;
protected const PROTECTED_CONST = 0;
public const PUBLIC_CONST = 0;
}
As of PHP7.1 visibility modifiers are allowed for class constants, in previous versions it's not possible to set the visibility of constants in a class. 从PHP7.1开始 ,允许修饰符用于类常量,在以前的版本中,不可能在类中设置常量的可见性。 They're always public.
他们总是公开的。 See the comments at http://www.php.net/manual/en/language.oop5.constants.php for more information.
有关详细信息,请参阅http://www.php.net/manual/en/language.oop5.constants.php上的注释。
An alternative would be to use a Constant Method, eg 另一种方法是使用常数方法,例如
private static function gravitationalConstant() {
return 9.81;
}
Quoting from Fowler's Refactoring book : 引自福勒的重构书 :
This idiom is less familiar to C based programmers, but is very familiar to Smalltalkers (who didn't have constants in their language).
这个成语对于基于C的程序员来说不那么熟悉,但对于Smalltalkers(他们的语言中没有常量)非常熟悉。 On the whole I don't tend to use this in Java as it is less idiomatic to the language.
总的来说,我不倾向于在Java中使用它,因为它不太习惯于语言。 However if you need to replace the simple return with a calculated value then it's worth changing the constant field to a constant method.
但是,如果需要使用计算值替换简单返回,则值得将常量字段更改为常量方法。 (I guess there should be a refactoring for that....)
(我想应该有重构......)
In PHP Latest version (PHP 7.1.0) it will available. 在PHP最新版本(PHP 7.1.0)中它将可用。
Sample Syntax was like. 样本语法就像。
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;
}
Refer below link. 请参阅以下链接。 https://wiki.php.net/rfc/class_const_visibility
https://wiki.php.net/rfc/class_const_visibility
现在可以在PHP 7.1发布Alpha今天添加Class常量可见性修饰符
It is possible in Php 7.1.0. 在Php 7.1.0中是可能的。 Please visit PHP RFC: Support Class Constant Visibility
请访问PHP RFC:支持类常量可见性
Modifiers are not allowed for constants in php. php中的常量不允许使用修饰符。 You can use
您可以使用
public static $variable = "abc";
but sadly final
is not allowed here. 但遗憾的是,
final
不允许在这里举行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.