Are private constants possible in PHP?

user656925 picture user656925 · Apr 19, 2012 · Viewed 33.6k times · Source

PHP does not allow

class Foo
{
    private const my_private_const;

but of course allows

const my_const;

So in effect constants are global because I can access my_const anywhere using Foo::my_const

Is there a way to make private constants?

Answer

Tahir Yasin picture Tahir Yasin · Dec 2, 2016

Folks! PHP 7.1.0 has been released

Now it's possible to have visibility modifiers with class constants.

<?php
class Foo {
    // As of PHP 7.1.0
    public const BAR = 'bar';
    private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
?>

Output of the above example in PHP 7.1:

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …