Constants inside quotes are not printed?

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.


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

echo "This is a constant: " . CONSTANT;

The dot is the concatenation operator.


Concatenation has been suggested as the only solution here, but that doesn't work when using syntax like:

    define("MY_CONSTANT", "some information");
    $html = <<< EOS
    <p>Some html, **put MY_CONSTANT here**</p>
EOS;

Of course, the above just puts the text 'MY_CONSTANT' in $html.

Other options include:

  • define a temporary variable to hold the constant:

        $myConst = MY_CONSTANT;
        $html = <<< EOS
        <p>Some html, {$myConst} </p>
    EOS;
    
  • if there are many constants, you can get an array of them all and use that:

        $constants = get_defined_constants();
        $html = <<< EOS
        <p>Some html, {$constants["MY_CONSTANT"]} </p>
    EOS;
    

Of course, in such a trivially short example, there's no reason to use the <<< operator, but with a longer block of output the above two may be much clearer and easier to maintain than a bunch of string concatenation!


define('QUICK', 'slow');
define('FOX', 'fox');

$K = 'strval';

echo "The {$K(QUICK)} brown {$K(FOX)} jumps over the lazy dog's {$K(BACK)}.";

Tags:

Php