PHP EOF (heredoc) Usage Instructions
PHP EOF (heredoc) is a method to define a string in command line shells (such as sh, csh, ksh, bash, PowerShell, and zsh) and programming languages (like Perl, PHP, Python, and Ruby).
Usage Overview:
- Must be followed by a semicolon, otherwise, the compilation will not pass.
- EOF can be replaced with any other characters, as long as the end identifier is consistent with the start identifier.
3. The end identifier must be at the beginning of a line and stand alone (i.e., it must start at the beginning of the line, with no preceding or following spaces or characters).
- The start identifier can be unquoted or quoted with single or double quotes. Unquoted or double-quoted identifiers will interpret embedded variables and escape symbols, while single-quoted identifiers will not interpret embedded variables and escape symbols.
- When content requires embedded quotes (single or double), no escape characters are needed, as it inherently escapes single and double quotes, similar to the usage of q and qq.
Example
<?php
echo <<<EOF
<h1>My First Heading</h1>
<p>My first paragraph.</p>
EOF;
// The end must be on a separate line with no preceding or following spaces
?>
Note:
Start with the
<<<EOF
start tag and end with theEOF
end tag. The end tag must be written at the beginning of the line, without indentation or spaces, and a semicolon must be at the end of the end tag.The start and end tags must be the same, such as commonly used uppercase
EOT
,EOD
,EOF
, but not limited to those (also can use: JSON, HTML, etc.), as long as the start and end tags do not appear in the text.Variables between the start and end tags can be parsed normally, but functions cannot. In heredoc, variables do not need to be concatenated with
.
, or,
, as shown below:
Example
<?php
$name = "tutorialpro";
$a = <<<EOF
"abc"$name
"123"
EOF;
// The end must be on a separate line with no preceding or following spaces
echo $a;
?>