PHP: echoing a constant with a variable name

20,794

Solution 1

Check out constant().

In your case:

echo constant($stuff . '_FOO');

Solution 2

First make a constant:

define("FOO_BAR", "something more");

then you can get the value by using constant():

echo constant("FOO_BAR");

Read more about constants in the manual.

Share:
20,794
Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on June 12, 2020

Comments

  • Alex
    Alex almost 4 years

    How can I do that?

    I have something like:

    define($stuff.'_FOO', 'whatever');
    echo $stuff.'_FOO';
    

    and it doesn't work :(

    I just want to echo the constant's value...

  • Jason McCreary
    Jason McCreary about 13 years
    Note the OP is creating the constant name from a variable. So $stuff is intentional.
  • Alex
    Alex about 13 years
    yes, and I have a justified reason :D (need it to generate error messages for a set of forms, and the constant name contains the form ID)