php 覆盖现有的定义常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5162333/
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
Override an existing defined constant
提问by MacMac
Possible Duplicate:
Can you assign values to constants with equal sign after using defined in php?
I'm not sure if it's just me, but how do you override an existing constant something like this:
我不确定这是否只是我,但是您如何覆盖现有的常量,如下所示:
define('HELLO', 'goodbye');
define('HELLO', 'hello!');
echo HELLO; <-- I need it to output "hello!"
//unset(HELLO); <-- unset doesn't work
//define('HELLO', 'hello!');
回答by 131
Truth is, you can, but you should not. PHP being an interpreted language, there is nothing you "can't" do. The runkit extension allow you to modify PHP internals behavior, and provide the runkit_constant_redefine(simple signature) function.
事实是,你可以,但你不应该。PHP 作为一种解释型语言,没有什么是你“不能”做的。runkit 扩展允许您修改 PHP 内部行为,并提供 runkit_constant_redefine(简单签名)函数。
回答by Gajahlemu
You can override a constant if it extended from a class. So in your case you can't override constant as it consider came from a same class. ie (taken from php manual):
如果常量是从类扩展而来的,则可以覆盖它。因此,在您的情况下,您不能覆盖常量,因为它认为来自同一类。即(取自 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
?>
If you turn on php error reporting ie:
如果您打开 php 错误报告即:
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
you will see a notice like
你会看到一个通知
Notice: Constant HELLO already defined in ....
回答by mardala
If the page is reloading, you can have a dynamic value change the constant.
如果页面正在重新加载,您可以使用动态值更改常量。
Like:
喜欢:
$random = something_that_gives_me_randomness();
define('HELLO', $random);
But if you are trying to change a constant in the same script, then linepogl is correct. Its called a constant for a reason.
但是如果你想在同一个脚本中改变一个常量,那么 linepogl 是正确的。它被称为常数是有原因的。