是否可以在 php heredoc 语法中编写 javascript?

Is it possible to write javascript in php heredoc syntax?

我正在尝试输出 Javascript 代码 heredoc 语法,我希望使用 PHP print_r 函数将其打印出来。可以吗?

PHP:

<?php
function printR($val){
    echo "<pre>";
    print_r($val);
    echo "</pre>";
}

$str = <<<EOT
    var msg = "Hello my name is ";
    var name = "Jermaine Forbes";
    function writeIt(m,n){
        console.log(m+n);
    }
    writeIt(msg,name);
    EOT;

printR($str);
?>

(来自@FirstOne:我保留了 EOT; 身份,因为有*关于它的评论)

是的,你可以。如果您希望字符串中只有 Javascript(没有 PHP 变量),我会使用 nowdoc 而不是 heredoc(在开头 EOT

周围使用单引号
$str = <<<'EOT'
            var msg = "Hello my name is ";
            var name = "Jermaine Forbes";
            function writeIt(m,n){

              console.log(m+n);
            }

            writeIt(msg,name);

EOT;

另请注意,结束分隔符必须单独出现在最后一行。在它之前或之后不能有任何 space。您的代码无法运行,因为您缩进了 EOT;From the docs:

Warning: It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon.