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). See the RFC : Support Class Constant Visibility.
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. They're always public. See the comments at http://www.php.net/manual/en/language.oop5.constants.php for more information.
An alternative would be to use a Constant Method, e.g.
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). On the whole I don't tend to use this in Java as it is less idiomatic to the language. 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.
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
Modifiers are not allowed for constants in php. You can use
public static $variable = "abc";
but sadly final
is not allowed here.
It is now possible in PHP 7.1 released Alpha today which adds Class constant visibility modifiers
It is possible in Php 7.1.0. Please visit PHP RFC: Support Class Constant Visibility
精彩评论