Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are private constants possible in PHP? [duplicate]

People also ask

Can constants be private?

Answer 5518b447937676d350004c42. Constants can be used with public or private just fine!

Are constants public or private?

Constants are meant to be public, because they are to describe immutable facts about the class, not the state or it. So there's no value in hiding them.

Can you redefine constants in PHP?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.

How many types of constant are there in PHP?

PHP constants can be defined by 2 ways: Using define() function. Using const keyword.


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 …

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


Note, that visibility modifiers for class constants have been added in PHP 7.1.

RFC: Support Class Constant Visibility


A simplified version of @Madbreaks' workaround: write a private static function that returns the value of your private "constant":

private static function MY_CONSTANT() {
    return "constant string";
}

Usage:

public static function DoStuff() {
    echo self::MY_CONSTANT();
}