22

I've seen some people using this code.

echo <<< EOT
Hi <br>
EOT;

and

echo <<< HTML
Hello<br>
HTML;

What's the difference of those two? and why would not they use the normal echo? like

echo "How are you<br>"?

3 Answers 3

26

Nothing, it's just a delimiter for the HEREDOC syntax. The only benefit of using HEREDOC is you can keep indents and structure of your string in the source code. It tends to be nicer to work with than concatenated strings - for your example Hi <br>, there is no good reason to use HEREDOC.

4
  • 3
    i only use HEREDOC for js as it saves escaping when using " and ' otherwise the standard methods
    – user557846
    Mar 3, 2013 at 5:19
  • Ya I tend to use NOWDOC almost exclusively these days since I'm so used to single-quoting my strings. Mar 3, 2013 at 5:20
  • 5
    To answer his question about the difference between the two (EOT vs HTML): There is no difference in terms of function. Both are It's up to the developer to decide the identifier that will denote the beginning and end of the "HEREDOC". You should take care to use an identifer that won't show up in the string itself. Using EOT versus HTML is like the difference between naming a variable $foo versus $bar. The function is the same, just the name is different. Mar 3, 2013 at 5:22
  • The delimiter can show up in the string, just make sure the string is indented, as the closing delimiter HAS to be at the 0 column. (Far left of the line) Mar 3, 2013 at 5:33
6

May be very very very late to comment but, in context of today's IDEs: When you use HEREDOCS the identifiers provide a hint as to what kind of information is being stored

Say <<<SQL the IDE's syntax highlighter may use the SQL identifier for highlighting the contents of the string as an SQL Query. <<<HTML for HTML highlighting ... and so forth.

0
5

why would not they use the normal echo?

Using heredoc for this very example makes no sense.
And it's indeed to use echo to print out single text line.
So, nobody is using heredoc for this.

Also, in echoing large text blocks heredoc is useless again, as one have to just close PHP tag and write the text as is.

The only use of heredoc is when you need to store a large block of text in a variable.

$var = <<< HERE
Hello %s!
Please follow this link %s to continue registration.
HERE;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.