PHP Strings Primer - Heredoc
(Page 5 of 37 )
This method of enclosing strings can look a little strange to some. It not very commonly used, but provides good functionality. With this technique, you do not need to worry about escaping single or double quotes because it uses neither. For this reason alone, it is appealing to some developers that dislike the chore of escaping quotation marks. We are not going to dwell on this method, but will just provide a simple example and brief explanation.
<?php $mystring = <<<EOD Hello World! This is the second line! EOD; ?> |
The EOD portion of this syntax is user definable. The important part of this syntax is remembering that the final EOD; must be on a line by itself and must not be indented at all. Everything, up until the closing EOD, will be assigned verbatim to the string. This includes if you forget to close one heredoc and then use another one later on. In this case, everything between the two heredocs will be assigned to the variable from the first. No errors will occur, as it is valid PHP code. Here is an example where we have forgotten to close a heredoc statement.
<?php $mystring = <<<EOD Hello World! This is the second line!   $myotherstring = <<<EOD Goodbye! EOD; ?> |
Other than the benefits of not having to escape quotation characters, this syntax also does variable substitution like the double quotes method. As with the double quotes, you must use the complex syntax when dealing with arrays and objects.
Next: Concatenation >>
More Programming Basics Articles
More By Matt Wade