覆盖现有的已定义常量

php
2022-08-30 22:12:00

可能的重复:
在php中使用定义后,是否可以将值分配给具有等号的常量?

我不确定是否只是我,但是你如何覆盖现有的常量,如下所示:

define('HELLO', 'goodbye');
define('HELLO', 'hello!');

echo HELLO; <-- I need it to output "hello!"

//unset(HELLO); <-- unset doesn't work
//define('HELLO', 'hello!'); 

答案 1

事实是,你可以,但你不应该.PHP作为一种被解释的语言,没有什么是你“不能”做的。runkit 扩展允许您修改 PHP 内部行为,并提供runkit_constant_redefine(简单签名)功能。


答案 2

如果常量是从类扩展而来的,则可以重写该常量。所以在你的情况下,你不能覆盖常量,因为它认为来自同一个类。即(取自php手册):

<?php

class Foo {
    const a = 7;
    const x = 99;
}

class Bar extends Foo {
    const a = 42; /* overrides the `a = 7' in base class */
}

$b = new Bar();
$r = new ReflectionObject($b);
echo $r->getConstant('a');  # prints `42' from the Bar class
echo "\n";
echo $r->getConstant('x');  # prints `99' inherited from the Foo class

?>

如果你打开php错误报告,即:

ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

你会看到一个通知,如

Notice: Constant HELLO already defined in ....

推荐