11

How do you use define within a heredoc? For example:

define('PREFIX', '/holiday');

$body = <<<EOD
<img src="PREFIX/images/hello.png" />   // This doesn't work.
EOD;
hakre
  • 193,403
  • 52
  • 435
  • 836
moey
  • 10,587
  • 25
  • 68
  • 112

3 Answers3

11

taken from the documentation regarding strings

DEFINE('PREFIX','/holiday');

$const = PREFIX;

echo <<<EOD
<img src="{$const}/images/hello.png" /> 
EOD;
Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
7

if you have more than 1 constant, variable usage would be difficult. so try this method

define('PREFIX', '/holiday');
define('SUFFIX', '/work');
define('BLABLA', '/lorem');
define('ETC', '/ipsum');

$cname = 'constant'; // if you want to use a function in heredoc, you must save function name in variable

$body = <<<EOD
<img src="{$cname('PREFIX')}/images/hello.png" />
<img src="{$cname('SUFFIX')}/images/hello.png" />
<img src="{$cname('BLABLA')}/images/hello.png" />
<img src="{$cname('ETC')}/images/hello.png" />
EOD;

http://codepad.org/lA8L2wQR

MC_delta_T
  • 596
  • 1
  • 9
  • 22
  • I followed your suggestion to try that because I thought it is interesting, however it came to my mind that your suggestion looks untested, because it gives many errors. – hakre Sep 24 '12 at 08:06
  • (Hmm. Crazy. I would've never....) Any thoughts on speed in comparison to @nbonniot answer: http://stackoverflow.com/questions/10041200/interpolate-constant-not-variable-into-heredoc#answer-30777936 – Ricalsin May 06 '16 at 18:15
3

Constants used within the heredoc syntax are not interpreted!

Editor's Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.

Source

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • Looks like that there is an exception to that rule: http://stackoverflow.com/a/12508992/367456 – hakre Sep 24 '12 at 08:07