12

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; 
0

3 Answers 3

12

taken from the documentation regarding strings

DEFINE('PREFIX','/holiday'); $const = PREFIX; echo <<<EOD <img src="{$const}/images/hello.png" /> EOD; 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Adding a little note: $const/images/hello.png will also work.
curly brackets are not required in this example.
Also you can use $consts = get_defined_constants(); to get all define and then access with {$consts['PREFIX']}.
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

2 Comments

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.
(Hmm. Crazy. I would've never....) Any thoughts on speed in comparison to @nbonniot answer: stackoverflow.com/questions/10041200/…
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

1 Comment

Looks like that there is an exception to that rule: stackoverflow.com/a/12508992/367456

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.