您可以在 PHP 中取消定义或更改常量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6455877/
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
Can you undefine or change a constant in PHP?
提问by TheConstantGardener
Can you undefine or change a constant in PHP?
您可以在 PHP 中取消定义或更改常量吗?
回答by George Cummins
回答by Patrick Steil
I know this is late to the game... but here is one thing that might help some people...
我知道这已经晚了……但这里有一件事可能会对某些人有所帮助……
In my "Application.php" file (where I define all my constants and include in all my scripts) I do something like this:
在我的“Application.php”文件中(我定义了所有常量并包含在我所有的脚本中)我做这样的事情:
if( !defined( "LOGGER_ENABLED" )){
define( "LOGGER_ENABLED", true );
}
So normally, every script is going to get logging enabled... but if in ONE particular script I don't want this behavior I can simply do this BEFORE I include my Application.php:
所以通常情况下,每个脚本都会启用日志记录......但如果在一个特定的脚本中我不想要这种行为,我可以在包含我的 Application.php 之前简单地执行此操作:
define( "LOGGER_ENABLED", false );
回答by Nils Luxton
If you absolutely need to do this (although I wouldn't recommend it as others have stated) you could always use Runkit.
如果您绝对需要这样做(尽管我不会像其他人所说的那样推荐它),您可以随时使用 Runkit。
http://www.php.net/manual/en/function.runkit-constant-redefine.php
http://www.php.net/manual/en/function.runkit-constant-redefine.php
http://www.php.net/manual/en/function.runkit-constant-remove.php
http://www.php.net/manual/en/function.runkit-constant-remove.php
回答by Colin
No. Once a constant is defined, it can never be changed or undefined.
不可以。一旦定义了常量,就永远不能更改或取消定义。
回答by Nick Rice
As not mentioned elsewhere, the uopz extension allows a constant to be deleted via uopz_undefine(), for PHP 5.4+.
正如其他地方没有提到的,对于 PHP 5.4+,uopz 扩展允许通过 uopz_undefine() 删除一个常量。
回答by Scott C Wilson
The other posters are correct - you can't do this. But perhaps you can move your definition to the point where you know what the best value for the constant would be.
其他海报是正确的 - 你不能这样做。但也许您可以将您的定义移动到您知道常量的最佳值是什么的程度。
Perhaps you're defining constants in a big list:
也许您正在一个大列表中定义常量:
define('STRING1','Foo');
define('STRING2', 'Bar');
define('STRING3', 'Baz');
and you want to change the value of STRING2 once you discover a condition. One way would be to defer the definition until you know the correct setting.
并且您想在发现条件后更改 STRING2 的值。一种方法是推迟定义,直到您知道正确的设置。
define('STRING1','Foo');
// define('STRING2', 'Bar'); -- wait until initialization
define('STRING3', 'Baz');
...
if (condition) {
define('STRING2', 'Bar type 2');
} else {
define('STRING2', 'Bar type 1');
}
The logic setting STRING2 could even be in a different file, later on in your processing.
逻辑设置 STRING2 甚至可以在不同的文件中,稍后在您的处理中。