[SOLVED] external constants with dynamic name?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

[SOLVED] external constants with dynamic name?

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post 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);
Post Reply