Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: echoing a constant with a variable name

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...

like image 524
Alex Avatar asked Apr 12 '11 02:04

Alex


People also ask

Can you redefine a constant in PHP?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT. Short answer: No.

How do you declare a constant variable in PHP?

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of define() function in PHP.

What are the differences between PHP constants and variables?

In PHP, the constant is an identifier or a name for a simple value. The constant value can't be changed during script execution. In PHP, the variable is a name or symbol which stands for value and used to store values such as characters, numeric, character string and memory addresses.


2 Answers

Check out constant().

In your case:

echo constant($stuff . '_FOO');
like image 103
Jason McCreary Avatar answered Sep 21 '22 12:09

Jason McCreary


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.

like image 35
Jaime Rodriguez Avatar answered Sep 23 '22 12:09

Jaime Rodriguez