PHP: how to redefine constants


Method 1: (for PHP >= 5.6)

In PHP 5.6+, you can import constants, under an alias. Such alias can overwrite an already existing constant.

Example:

define('MY_CONSTANT', 1);
define('TEMP_CONSTANT', 2);
use const TEMP_CONSTANT as MY_CONSTANT;
var_dump(MY_CONSTANT);  //int(2) 

Method 2: for PHP < 7.3.0 Use 3rd param as true.

Example:

define('MY_CONSTANT', 1, true);
var_dump(MY_CONSTANT); //int(1)
define('MY_CONSTANT', 2);
var_dump(MY_CONSTANT); //int(2)

Note: Defining case-insensitive constants is deprecated as of PHP 7.3.0

Method 3:
With the runkit7 extension, you can use runkit7_constant_redefine():

runkit7_constant_redefine("MY_CONSTANT", 2);

Leave a Reply