phpconstantsprivate

Are private constants possible in PHP?


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?


Solution

  • Update

    As of PHP 7.1 private constants are natively supported.

    Original Answer

    The answer is a simple "no". PHP doesn't support this concept. The best you can do is a private static variable in the class, which isn't as good of course because it's not readonly. But you just have to work around it.

    Edit

    Your question got me thinking - here's something I've never tried, but might work. Put another way "this is untested". But say you wanted a "private constant" called FOO:

    // "Constant" definitions
    private function __get($constName){
        // Null for non-defined "constants"
        $val = null;
        
        switch($constName){
            case 'FOO':
                $val = 'MY CONSTANT UNCHANGEABLE VALUE';
                break;
            case 'BAR':
                $val = 'MY OTHER CONSTANT VALUE';
                break;
        }
        
        return $val;
    }
    

    Of course your syntax would look a bit odd:

    // Retrieve the "constant"
    $foo = $this->FOO;
    

    ...but at least this wouldn't work:

    $this->FOO = 'illegal!';
    

    Maybe something worth trying?

    Cheers