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, 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). 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
现在可以在PHP 7.1发布Alpha今天添加Class常量可见性修饰符
It is possible in Php 7.1.0. Please visit PHP RFC: Support Class Constant Visibility
Modifiers are not allowed for constants in php. You can use
public static $variable = "abc";
but sadly final
is not allowed here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.