Page 1 of 1

[SOLVED] external constants with dynamic name?

Posted: Thu Mar 03, 2005 7:14 am
by jasongr
Hello

I have 1 php file called defines.php with the following definition:

Code: Select all

define("Age_Dog", 7);
a second php file called defines.php (different folder) with the following definition:

Code: Select all

define("Age_Cat", 3);
In my code include the correct file using:

Code: Select all

require_once(<path to file>/defines.php);
Now I have access to either Age_Dog or Age_Cat depending on what file was included.

I have a variable called $animal which indicates which constant is available. The value of the $animal variable is either 'Dog' or 'Cat'

I would like to define one variable called $animalAge which will hold the correct age depending on what file was included

I tried doing:

Code: Select all

eval('\$animalAge = "Age_"' . $animal );
When I then try to refer to the $animalAge variable, I get an error that variable $animalAge isn't defined

does anyone know how I can do this?
I am looking for a solution using eval (not if else and other conditionals)

regards

Posted: Thu Mar 03, 2005 8:07 am
by feyd

Posted: Thu Mar 03, 2005 8:10 am
by jasongr
Thanks

I indeed got a nice solution from Mark Baker which doesn't use eval:

Code: Select all

define("Age_Dog", 7); 
define("Age_Cat", 3); 

$animal='Cat'; 
$animalAge ='Age_'.$animal; 

echo "Defined value for $animalAge = "; 
echo constant($animalAge);