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';
Constants are private by default. Within procedures, constants are always private; their visibility can't be changed. In standard modules, the default visibility of module-level constants can be changed by using the Public keyword.
PHP - Class ConstantsClass constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
Default is public. Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With