Reputation: 5042
Is it possible to redefine a constant in php which was defined by the define
function?
I have a class with several constants that contains the user data. I'm trying to use the class for more than one user.
define('ALLEGRO_ID', 'id');
define('ALLEGRO_LOGIN', 'login');
define('ALLEGRO_PASSWORD', 'passwd');
define('ALLEGRO_KEY', 'key');
define('ALLEGRO_COUNTRY', 123);
$allegro = new AllegroWebAPI( );
$allegro -> Login();
I did not write this class, but I am using it due to time constraints. I do not know why the creator of this class defined
the user data rather than using the variables in the instance.
I know that constants should be constant (obviously!), but I'm looking for a trick to redefine them.
Upvotes: 46
Views: 82818
Reputation: 2321
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;
Upvotes: 6
Reputation: 1421
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;
.
Upvotes: 23
Reputation: 87
Constants value once defined remains unchanged throughout the program. If you have such a requirement where you want to change the values in future then keep such values in PHP variables.
Upvotes: 4
Reputation: 47331
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;
}
}
Upvotes: 25
Reputation:
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.
Upvotes: 60