在php中heredoc vs nowdoc的优点/不便

Mat*_*ieu 41 php heredoc nowdoc

作为一个新手,我被建议最好使用heredoc与太多嵌套代码相比(参见php代码中的意外T_ELSE).

但我无法理解heredoc和nowdoc之间是否存在显着差异.

与另一个对新手理解很重要的东西(即不是很小的优点但对我理解很重要)相比,heredoc和nowdoc有什么优势.

dec*_*eze 106

Nowdocs是单引号字符串,heredocs是双引号字符串.类似于heredoc指定了nowdoc,但是在nowdoc内部没有进行解析.该构造非常适合嵌入PHP代码或其他大块文本而无需转义.

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

换一种说法:

$foo = 'bar';

$here = <<<HERE
    I'm here , $foo !
HERE;

$now = <<<'NOW'
    I'm now , $foo !      
NOW;
Run Code Online (Sandbox Code Playgroud)

$here"我在这里,吧!" ,虽然$now"我现在,$ foo!" .

如果您不需要变量插值但需要特殊字符,比如$字符串内部,则Nowdocs更易于使用.就这样.