Redefining constants in PHP
In PHP 5.6+, you can import constants, under an alias. Such alias can overwrite an already existing constant.
The following snippet will print int(5)
:
define('ALLEGRO_ID', 3);
define('NEW_ALLEGRO_ID', 5);
use const NEW_ALLEGRO_ID as ALLEGRO_ID;
var_dump(ALLEGRO_ID);
Such mechanism could be legitimate in unit test, or other areas where magic behavior is tolerated, but isn't convenient for your use case, where a class to store your user settings would be more useful.
Finally, this behavior allows to create very confusing situations like use const true as false;
.
No, you cannot redefine a constant (except with runkit_constant_redefine),
that's why is called CONSTANT.
What you are looking for in the class is actually an object variable in array format:-
class user
{
public $user = array();
function load($user_id)
{
// etc
$this->$user[$user_id] = something_else;
}
}
passing 3rd param as true will help you
define('CONSTANT_NAME', 'constant_value', true);
print CONSTANT_NAME.PHP_EOL;
define('CONSTANT_NAME', 'constant_value2');
print CONSTANT_NAME.PHP_EOL;
https://ideone.com/oUG5M9
If you have the runkit extension installed, you can use runkit_constant_redefine()
:
runkit_constant_redefine("name", "value");
In most circumstances, however, it would be a better idea to re-evaluate why you're using constants and not something more fitting.