Heredoc and Nowdoc in PHP

Heredoc is to double-quoted string. So the inside can be parsed if there is variable. There is bug associated with Heredoc, namely the line with the closing identifier must contain no other characters, except possibly a semicolon (;). Example:

$err = ‘Parse error, unexpected $end in this.php on line xx’;
<<<HEREDOC
This is to show error message “$err” if you put whitespace either at front or end of closing line.
HEREDOC

Nowdocs are to single-quoted strings however. So a nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. This is very useful to parse a large block of embedded dynamic codes. Example:

<<<’NOWDOC’
Within this block, though $err is a variable, the final result would be exactly same as what you are seeing now. The variable “$err” won’t be parsed.
NOWDOC

No escape needed for both methods.

In addition, although you can use any word for heredoc and nowdoc purpose, it is recommended using exactly these words to emphasis the difference as well as the help you to remember what these techniques are called.

http://ca2.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

No comments:

Post a Comment

Labels