PHP supports Heredoc and Newdoc syntax. It is a convenient way to assign multiple lines string to a variable. This makes code more readable. Here is quick code snippets for it.
Using php heredoc
<?php $a = "hello"; $s = <<<EOM Line1 $a Line2 EOM; echo "==========\n"; echo $s; echo "==========\n"; ?>
========== Line1 hello Line2==========
Env: PHP 7.4.33 (Linux)
Few points about PHP heredoc
- Heredoc identifier can be anything. The closing heredoc identifier must start in the beginning of line and end with
;
- Last newline does not become part of variable.
- Other variables get evaluated in heredoc
Using php newdoc
Newdoc is similar to heredoc but variables are not expanded. This is useful for assigning code snippets etc. Newdoc beginning identifier is within single quotes. Example and outcome using newdoc:
<?php $a = "hello"; $s = <<<'EOM' Line1 $a Line2 EOM; echo "==========\n"; echo $s; echo "==========\n"; ?>
========== Line1 $a Line2==========
Env: PHP 7.4.33 (Linux)
Note that $a is not expanded with newdoc syntax.