Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining constants in PHP

Tags:

php

constants

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.

like image 414
abuduba Avatar asked Dec 11 '11 15:12

abuduba


People also ask

Can you redefine a constant in PHP?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.

What is the purpose of _class_ constant?

Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.

How many types of constant are there in PHP?

PHP constants can be defined by 2 ways: Using define() function. Using const keyword.

What is the purpose of constant () function in PHP?

The constant() function returns the value of a constant. Note: This function also works with class constants.


1 Answers

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.

like image 193
Tim Cooper Avatar answered Sep 17 '22 20:09

Tim Cooper