简体   繁体   English

如何从另一个常量变量创建静态类常量变量?

[英]How to create static class constant variable from another constant variable?

I have a constant called PREFIX defined in constants.php. 我在constants.php中定义了一个名为PREFIX的常量。 In class Foo, I would like to create a static class constant with PREFIX as the prefix. 在类Foo中,我想创建一个以PREFIX作为前缀的静态类常量。 But I get a syntax error on that const definition line. 但是我在const定义行上遇到语法错误。

require_once 'constants.php';

class Foo {
    const FOO_CONST = PREFIX . 'bar';

    public function __construct() {
    }
}

In PHP a const must be a value, not an expression. 在PHP中, const必须是值,而不是表达式。 So const FOO_CONST = 'foo' . 'bar'; 所以const FOO_CONST = 'foo' . 'bar'; const FOO_CONST = 'foo' . 'bar'; won't work either. 也不行。

You have to use define or a class member that gets initialized in the constructor instead of a const . 您必须使用在构造函数而不是const初始化的define或类成员。 Initializing a class member outside a class method with an expression does not work either. 使用表达式在类方法外部初始化类成员也不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM