将 PHP Heredoc 与 Javascript 模板文字相结合

Combining PHP Heredoc with Javascript Template literals

我正在尝试在 PHP HEREDOC 段中使用模板文字。这会导致模板中使用的美元符号出现问题:

echo <<<JS
   console.error(`Source type ${source} not supported`);
JS;

给我以下错误:

PHP Notice:  Undefined variable: source in example.php on line 2

是否可以避免 PHP 将美元符号解析为变量?

使用 Nowdoc 而不是 heredoc

$myline = 'add this line';
$input = <<<'JS'
   console.error(`Source type ${source} not supported`);
   console.log(`%s`);
JS;
$output = sprintf($input,$myline);
echo $output

如@ChrisG 的评论所述,只需添加反斜杠即可解决问题:

echo <<<JS
   console.error(`Source type ${source} not supported`);
JS;