PHP Class Constants - Public, Private or Protected?

Historically, class constants were always publicly accessible as long as the class was loaded and there was no way to change this.

As of PHP 7.1, they remain public by default but access modifiers may now be applied. Here's the example from the release notes:

<?php
class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}

Class constants should have the option of being private/protected because being public exposes internal details of the class that other classes/code can mistakingly use thinking they are ok to use because they are public.

It would be nice to know that changing a private constant would ONLY affect the class it's defined in. Unfortunately we don't have that option.

Remember back to when you were learning Object Design & Analysis... you give class methods and attributes the most RESTRICTIVE access possible, and later relax them as needed (much harder to go back the other way because other classes/code start using them which would then break other code).

WORKAROUND

Best bet is to just create a private or protected variable and upper-case it to show it's a constant. You could always create a class called constant($value_to_be_constant) that implements the correct magic methods / spl interfaces to prevent it from being changed.

Tags:

Php

Constants