2

I've seen HTML nested within a PHP page written in so many ways... some of which are demonstrated in this page: http://austingulati.com/2010/01/many-ways-to-integrate-html-into-php/

But... I very rarely see HTML and PHP written in unison as follows:

echo <<<EOF
<h1>Welcome</h1>
<p>Hello</p>
<p>{$somePHPVariable}</p>
EOF;

Question:

Is there a fundamental issue with using the EOF approach that I should be aware of?

Jack
  • 15,614
  • 19
  • 67
  • 92

3 Answers3

5

This is called heredoc syntax (the "EOF" can be any identifier, not just "EOF"). It's a little more finicky than the other string syntaxes, and it can be a little confusing to folks who haven't encountered it before. Perfectly fine to use, though.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
5

Heredocs are wonderful if you're building HTML and need to embed variables.

They honor the linebreaks/spacing you embed within them (even if the browser doesn't display that) so it's MUCH easier to build nicely formatted HTML, and also relieve you of the need to escape quotes while building the strings:

e.g. compare

print("<div class=\"this\">\n\tblah blah\n\t\t<span class=\"that\">blah</span>\n</div>");

v.s.

echo <<<EOL
<div class="this">
    blah blah
        <span class="that"</span>
</div>
EOL;

They can also be used in concatenation operations, eg.

$x = "hello";
$x .= <<<EOL
  there, how 
EOL
$x .= <<<EOL
  are you?
EOL;

will eventually give $x the value hello there, how are you?. Basically consider the heredoc syntax to be a VERY fancy version of double-quoted strings, with none of the drawbacks. The only restriction is that the heredoc's sentinal value must be on a line by itself, so there's no way to make a "one line" heredoc.

Marc B
  • 356,200
  • 43
  • 426
  • 500
2

Heredoc syntax is actually great! It is very useful for situations where you have data with lots of single quotes and double quotes.

I've gone into some of the details of it before here: Quoting quotation marks

One of the downsides to it I find is that it does tend to disable syntax highlighting in editors because the editor views it as one big string and therefore won't properly highlight html inside.

Another downside is not being able to directly call functions from within heredoc syntax. There are workarounds and a few of them are mentioned here: Calling PHP functions within HEREDOC strings

Community
  • 1
  • 1
Jared
  • 12,406
  • 1
  • 35
  • 39
  • 1
    Syntax highlighting is problematic -- and the fact that the terminal token has to be left-aligned to work defaces otherwise beautiful code =( – Kevin Nielsen May 01 '12 at 20:55