PHP - Constants and variables

jjones

Lifer
Oct 9, 2001
15,424
2
0
In PHP you can create variable variables. Is there any way to do something similar with constants?

I'm using some variable variables like this:

$a = 'cat';

$b = 'a';

$c = $$b; (which is the same as $c = 'cat';)

I want to do the same type of thing with a constant, where I've got the name of the constant as a string attached to a variable, and then want to use that variable to call the constant.

Any way to do this?
 
Jun 4, 2005
19,723
1
0
Not sure if I understand what you're saying, but this is what I think you're asking:

define("constant", "hey");
$var = constant;
echo constant; //outputs hey
echo $var; //outputs hey

 

jjones

Lifer
Oct 9, 2001
15,424
2
0
Yep, that's what I'm talking about, but when you echo the variable, it won't output the constant value.

Actually, that's not quite what I'm doing. What you do works as it should. What I'm doing is like this:

define('_CONSTANT','hey');

$a = 'CONSTANT';

$b = '_'.$a;

echo $b;

That will output the string '_CONSTANT', not the constant value 'hey'. I want it to output that value.
 

troytime

Golden Member
Jan 3, 2006
1,996
1
0
seems like none of the dynamic variable techniques work for constants

might wanna mess around with eval, maybe something will work
good luck
 

jjones

Lifer
Oct 9, 2001
15,424
2
0
Well, this was so simple I feel stupid.

define('_CONSTANT','hey');

$a = STANT;

$b = '_CON'.$a;

echo constant($b); - outputs 'hey'