Search code examples
phpdynamic-variables

How do I get a constant's value when forming its name dynamically?


That title probably doesn't help much. I'm trying to figure out if there's a way to get the value of a variable that has been set using define(...), but using a 2nd variable to build the defined var's name. Example will be clearer:

define('I_LOVE_YOU', 'xoxox');
$n = 'LOVE';

// how to get 'xoxox', using $n?  This won't work:
$defd = 'I_'.$n.'_YOU';
echo $defd;  // obviously echos 'I_LOVE_YOU', not 'xoxox'

// this will, but is awful
eval('echo I_'.$n.'_YOU;');  // echos 'xoxox'

Is there any other way to do this, w/o resorting to eval?


Solution

  • Don't use eval(), use constant():

    define('I_LOVE_YOU', 'xoxox');
    $n = 'LOVE';
    echo constant('I_'.$n.'_YOU');