Search code examples
phpsyntaxconstantsheredoc

Interpolate a constant (not variable) into 'heredoc'


Consider:

<?php
   define('my_const', 100);
   echo <<<MYECHO
      <p>The value of my_const is {my_const}.</p>
MYECHO;
?>

If I put a variable inside the braces, it prints out. But not the constant. How can I do it?


Solution

  • Use sprintf()

    define('my_const', 100);
    $string = <<< heredoc
          <p>The value of my_const is %s.</p>
    heredoc;
    
    $string = sprintf($string, my_const);