| PHP Nowdocs Posted by: John in PHP on Aug 17, 2008 |
A few weeks ago Jordan blogged about the heredoc syntax. The point I want to raise in this blog, is the heredoc syntax parses PHP code, similar to double quotes around a string. For example
Would output
The output now is

- $name = "John";
- $john = <<<EOD
- Hello World!<br />
- EOD;
- $world = <<<EOD
- Hi $name!<br /><br >
- EOD;
$name = "John";
$john = <<<EOD
Hello World!<br />
EOD;
$world = <<<EOD
Hi $name!<br /><br >
EOD;
$john = <<<EOD
Hello World!<br />
EOD;
$world = <<<EOD
Hi $name!<br /><br >
EOD;
Hello World!Notice $name was parsed as a variable not as a literal. Until PHP 5.3 the only option to store and echo literal php code was to use single quotes around the code. However, you now have the option to use the nowdoc syntax. To use the nowdoc syntax all you have to do is place single quotes around the identifier. Using the nowdoc syntax our previous example becomes:
Hi John!

- $name = "John";
- $john = <<<'EOD'
- Hello World!<br />
- EOD;
- $world = <<<'EOD'
- Hi $name!<br /><br >
- EOD;
$name = "John";
$john = <<<'EOD'
Hello World!<br />
EOD;
$world = <<<'EOD'
Hi $name!<br /><br >
EOD;
$john = <<<'EOD'
Hello World!<br />
EOD;
$world = <<<'EOD'
Hi $name!<br /><br >
EOD;
Hello World!
Hi $name!