PHP 中可以使用私有常量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10232434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:43:06  来源:igfitidea点击:

Are private constants possible in PHP?

phpconstprivate

提问by Tahir Yasin

PHP does not allow

PHP 不允许

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_constanywhere using Foo::my_const

所以实际上常量是全局的,因为我可以使用my_const任何地方访问Foo::my_const

Is there a way to make private constants?

有没有办法制作私有常量?

采纳答案by Madbreaks

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

答案是一个简单的“不”。PHP 不支持这个概念。你能做的最好的事情是private static类中的一个变量,当然它不是那么好,因为它不是只读的。但你只需要解决它。

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:

你的问题让我思考 - 这是我从未尝试过但可能有效的方法。换句话说,“这是未经测试的”。但是假设您想要一个名为的“私有常量” 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

干杯

回答by Tahir Yasin

Folks! PHP 7.1.0 has been released

伙计们!PHP 7.1.0 已经发布

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:

以上示例在 PHP 7.1 中的输出:

bar

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

回答by user1636505

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

请注意,类常量的可见性修饰符已在 PHP 7.1 中添加。

RFC: Support Class Constant Visibility

RFC:支持类恒定可见性

回答by alexanderbird

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

@Madbreaks 解决方法的简化版本:编写一个私有静态函数,返回私有“常量”的值:

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

Usage:

用法:

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