我正在尝试根据 this answer 在 PHP 中执行类似按位枚举的操作.然而,虽然当我将所有常量定义为像这样的常规整数时它工作得很好:
final class CountryEnum {
const CZ = 1; //Czech Republic
const DE = 2; //Germany
const DK = 4; //Denmark
//12 more
const US = 32768; //USA
}
当我尝试通过移位模式定义值时它不起作用,即:
final class CountryEnum {
const CZ = 1; //Czech Republic
const DE = 1 << 1; //Germany
const DK = 1 << 2; //Denmark
//12 more
const US = 1 << 15; //USA
}
当我尝试运行它时,PHP 发出了一个合适的提示
Parse error: parse error, expecting
','' or
';'' in CountryEnum.php on line [the line with const DE]
所以我可能遗漏了一些基本的基本东西,但我不知所措。
最佳答案
PHP 5.6 之前的版本
您不能在 PHP 中通过表达式定义类常量或类属性,即使表达式的结果总是返回相同的值(如 1 << 2
)。这是因为类常量是在编译时而不是运行时定义的。参见 Class ConstantsDocs :
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
PHP 5.6 及更高版本
从 2014 年发布的 PHP 5.6 开始,常量标量表达式现在在语法上是有效的并且将被解析。
It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.
关于PHP 按位枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472802/