Can you undefine or chang开发者_如何学Ce a constant in PHP?
No. Constants are constant.
Reference: php.net/manual/language.constants.php
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:
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:
define( "LOGGER_ENABLED", false );
If you absolutely need to do this (although I wouldn't recommend it as others have stated) you could always use Runkit.
http://www.php.net/manual/en/function.runkit-constant-redefine.php
http://www.php.net/manual/en/function.runkit-constant-remove.php
No. Once a constant is defined, it can never be changed or undefined.
As not mentioned elsewhere, the uopz extension allows a constant to be deleted via uopz_undefine(), for PHP 5.4+.
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.
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.
精彩评论