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

问题描述 投票:0回答:2

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

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

给我以下错误:

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

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

javascript php heredoc template-literals
2个回答
0
投票
使用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


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

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

© www.soinside.com 2019 - 2024. All rights reserved.