PHP 字符串中的 Heredoc 和 Nowdoc

246 阅读1分钟

首先要了解下定界符

php可以使用

<?php
echo <<<EOT
this is body
this is body as well
EOT
;

这种方式来输出大段文字,其中EOT就是定界符,定界符有分为开始定界符和结束定界符,定界符可以是任何内容,只要保证开始定界符和结束定界符一致就行,比如

<?php
echo <<<AAA
this is body
this is body as well
AAA
;

这就是heredoc的写法,heredoc中的变量会被解析成具体的值

<?php
$a = 'this is string';
echo <<<AAA
this is body
this is body as well
$a
AAA
;
// output
this is body
this is body as well
this is string

如果希望内容不被解析,可以在开始定界符的两边加上单引号'EOT'

<?php
$a = 'this is string';
echo <<<'AAA'
this is body
this is body as well
$a
AAA
;
// output
this is body
this is body as well
$a

这就是nowdoc的写法