Search code examples
phpconstants

PHP Class Constants - Public, Private or Protected?


Am I correct in assuming that constant properties are automatically public? Is there a way to make them private or protected?


Solution

  • 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;
    }