black_yurizan black_yurizan - 4 months ago 24
PHP Question

Is it possible to write javascript in php heredoc syntax?

I'm trying to output Javascript code heredoc syntax and I want it to be printed out with the PHP

print_r
function. Is it possible to do that?

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);
?>


(by @FirstOne: I kept
EOT;
idented since there was* a comment about it)

Answer

Yes you can. If you expect to have only Javascript in the string (no PHP variable), I would use nowdoc instead of heredoc (use single quotes around the opening 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;

Note also that the closing delimiter must be alone on the final line. You can't have any space before or after it. Your code didn't work because you have indented 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.