像使用 define() 一样在 for 循环中创建常量

creating constants in a for loop as you can with define()

现在我正在使用的代码库在构造函数中做这样的事情:

$constants = array('CONSTANT1' => 1, 'CONSTANT2' => 2);
foreach ($constants as $name=>$val) {
    if (!defined($name) {
        define($name, $val);
    }
}

我想用 PHP5 const 代替。 IE。所以我可以做 if ($var == self::CONSTANT1).

而不是在代码中做 if ($var == CONSTANT1)

知道我该怎么做吗?

i would like to do this with PHP5 const's instead.

据我所知,如果没有 runkit 扩展,您无法在运行时在 PHP 中添加 class constants

然而,使用 runkit 扩展,您可以将其与 define 类似:runkit_constant_add.

runkit_constant_add(sprintf('%s::%s', get_class($this), $name), $val);

由于 runkit 扩展非常内部化,这强烈表明您的设计存在问题。

如果您可以接受变量,您可以考虑选择静态全局 class 变量。

正如您明确要求的那样:是的,安装(并帮助维护)runkit extension