Thursday, July 1, 2010

HEREDOC: a great way to build long strings

The PHP HEREDOC feature: a great way to build long strings, such as when You're writing PHP code to spit out HTML.  For example:

Hideous old method:
$my_string = "".
"<table>\n" .
"    <tr>\n".
"        <td>What's for lunch?</td>\n".
"    </tr>\n".
"</table>\n";

echo $my_string;

Magnificent Heredoc method:
$my_string = <<<COOLSTUFF
<table>
    <tr>
        <td>What's for lunch?</td>
    </tr>
</table>
COOLSTUFF;

echo $my_string;

see: http://www.tizag.com/phpT/strings.php

Note that the Heredoc syntax is rather unforgiving.  That terminating "COOLSTUFF" line must be NON-indented, and You can't even have spaces or tabs after it on the same line, or it won't work.  But if You treat it nice, it will treat You nice.

No comments:

Post a Comment

Constructive, concise comments are welcome.