tags:

views:

81

answers:

3

This prints apple:

define("CONSTANT","apple");
echo CONSTANT;

But this doesn't:

echo "This is a constant: CONSTANT";

Why?

+8  A: 

Because "constants inside quotes are not printed". The correct form is:

echo "This is a constant: " . CONSTANT;

The dot is the concatenation operator.

Artefacto
+2  A: 

If you want to include references to variables inside of strings you need to use special syntax. This feature is called string interpolation and is included in most scripting languages.

This page describes the feature in PHP. It appears that constants are not replaced during string interpolation in PHP, so the only way to get the behavior you want is to use the concatenation that Artefacto suggested.

In fact, I just found another post saying as much:

AFAIK, with static variables, one has the same 'problem' as with constants: no interpolation possible, just use temporary variables or concatenation.

jasonmp85
The reason why you cannot use the special syntax `{}` with constants is simple: The brackets are only recognized as "special syntax" if `{` is immediately followed by a `$`. But constants don't have that...
Felix Kling
The `$` is usually called a sigil. I haven't seen any hard and fast documentation that says string interpolations only works on variables and expressions with a `$`, but every example of string interpolation in PHP I can find uses it. grossvogel's postulation is probably the very reasonable reason that this is so.
jasonmp85
A: 
define('QUICK', 'slow');
define('FOX', 'fox');

$K = 'strval';

echo "The {$K(QUICK)} brown {$K(FOX)} jumps over the lazy dog's {$K(BACK)}.";
gregjor
In case it's not apparent, the big problem with the indirect function call technique is that $K is not in the global namespace, so it must be declared with `global $K;` in every function that needs to use it.
gregjor