PHP Heredoc
This tutorial will teach you how to use PHP heredoc and nowdoc strings to improve code readability.
When variables are placed in a double-quoted string, PHP expands the variable names. If a string contains double quotes (“), use the backslash character to escape them (\). As an example:
<?php $he = 'Bob'; $she = 'Alice'; $text = "$he said, \"PHP is awesome\". \"Of course.\" $she agreed."; echo $text;
Output
Bob said, "PHP is awesome". "Of course." Alice agreed.
PHP heredoc strings behave in the same way as double-quoted strings, but without the double-quotes. This means they don’t have to escape quotes or expand variables. As an example:
<?php $he = 'Bob'; $she = 'Alice'; $text = <<<TEXT $he said "PHP is awesome". "Of course" $she agreed." TEXT; echo $text;
PHP heredoc syntax
The syntax of a heredoc string is shown below:
<?php $str = <<<IDENTIFIER place a string here it can span multiple lines and include single quote ' and double quotes " IDENTIFIER;
This is how it works.
Begin with the operator, an identifier, and a new line:
<<<IDENTIFIER
Second, enter the string, which can span multiple lines and include single or double quotes (‘) or quotes (“).
Third, use the same identifier to close the string.
The identifier must begin with an underscore or a non-digit character and contain only alphanumeric characters and underscores.
The closing identifier must adhere to the following guidelines:
- Starts at the first column of the line.
- Other than a semicolon, there are no other characters (;).
- Before and after the closing identifier, the character must be a newline character defined by the local operating system.
- Because the character before it is not a newline character, the following heredoc string is invalid:
<?php $str = <<<IDENTIFIER invalid IDENTIFIER; echo $str;
The following heredoc string, on the other hand, is correct:
<?php $str = <<<IDENTIFIER valid IDENTIFIER; echo $str;
PHP heredoc strings’ use cases
In practise, the heredoc syntax is used to define a string containing a single quote, double quotes, or variables. The heredoc string improves the readability of the string.
A heredoc string can also be used to generate HTML dynamically. As an example:
<?php $title = 'My site'; $header = <<<HEADER <header> <h1>$title</h1> </header> HEADER; echo $header;
PHP Nowdoc syntax
A nowdoc string is similar to a heredoc string, with the exception that it does not expand the variables. The syntax of a nowdoc string is as follows:
<?php $str = <<<'IDENTIFIER' place a string here it can span multiple lines and include single quote ' and double quotes " IDENTIFIER;
The syntax of the nowdoc is similar to that of the heredoc, except that the identifier following the operator must be enclosed in single quotes. The nowdoc identifier follows the same rules as the heredoc identifier.