Can you undefine or change a constant in PHP?

后端 未结 6 1547
猫巷女王i
猫巷女王i 2020-12-16 09:18

Can you undefine or change a constant in PHP?

相关标签:
6条回答
  • 2020-12-16 09:42

    As not mentioned elsewhere, the uopz extension allows a constant to be deleted via uopz_undefine(), for PHP 5.4+.

    0 讨论(0)
  • 2020-12-16 09:46

    No. Once a constant is defined, it can never be changed or undefined.

    0 讨论(0)
  • 2020-12-16 09:50

    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

    0 讨论(0)
  • 2020-12-16 09:55

    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.

    0 讨论(0)
  • 2020-12-16 09:59

    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 );
    
    0 讨论(0)
  • 2020-12-16 10:00

    No. Constants are constant.

    Reference: php.net/manual/language.constants.php

    0 讨论(0)
提交回复
热议问题