Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define and heredoc

Tags:

php

heredoc

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;
like image 1000
moey Avatar asked Nov 23 '11 13:11

moey


3 Answers

taken from the documentation regarding strings

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

$const = PREFIX;

echo <<<EOD
<img src="{$const}/images/hello.png" /> 
EOD;
like image 125
Jan Dragsbaek Avatar answered Nov 19 '22 13:11

Jan Dragsbaek


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

like image 6
MC_delta_T Avatar answered Nov 19 '22 12:11

MC_delta_T


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

like image 3
codaddict Avatar answered Nov 19 '22 13:11

codaddict