views:

110

answers:

3

Toying with heredocs in PHP, I realized the name of the heredoc does not have to be unique. Thus:

$a = <<<EOD
Some string
EOD;

$b = <<<EOD
A different string
EOD;

is correct and behaves exactly as you would expect.

Is this bad practice for any reason? Why does a heredoc need a name/label (EOD above) at all, since you can't reference it by the name?

+2  A: 

You don't reference it as such, but it acts as an identifier to indicate the end of the heredoc. e.g.

$a = <<<EOD
EOA
EOB
EOC
EOD;
Brian Agnew
+2  A: 

What if the string you're specifying contains EOD?

You can select the identifier to avoid conflicts with the chunk of text you're using as a string.

ZoogieZork
exactly. then you use a different delimiter that isn't EOD. Note that the end of heredocs have to start on the first character of the line, which helps with specificity.Also note that substituted text is not scanned for the heredoc terminator - this means you can simply scan your code once for this simple mistake, and know you have not done it.
Alex Brown
A: 

One benefit is that editors like vim can apply syntax highlighting to heredocs named with HTML, EOHTML, EOSQL, EOJAVASCRIPT making them much prettier to work with...

$html = <<<EOHTML

<p class="foo">foo</em>

EOHTML;

$sql = <<<EOSQL

SELECT DISTINCT(name) FROM foo ORDER BY bar;

EOSQL;

$js = <<<EOJAVASCRIPT

foo = { bar: 'bar'; }

EOJAVASCRIPT;
Ken