php class constant visibility-ThrowExceptions

Exception or error:

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';


private const CONST_VALUE = 'A constant value';


protected const CONST_VALUE = 'A constant value';
How to solve:

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 for more information.


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;


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.


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

Leave a Reply

Your email address will not be published. Required fields are marked *