php - 在 PHP 的 heredoc 中使用变量

标签 php variables heredoc

我是 PHP/SQL 的新手,我想在 heredoc 中使用一个变量,因为我需要输出大量文本。我只包含了第一句话,因为它足以说明问题)。

我的问题是在 heredoc 中,变量(见下文:$data['game_name]$data['game_owner'])未被识别为变量,但作为纯文本。我该如何解决这个问题?

$response = $bdd->query('SELECT * FROM video_game');
while ($data = $response->fetch())
{

    echo <<<'EX'
    <p>Game: $data['game_name']<br/>
    the owner of the game is $data['game_owner']
    </p>
    EX;
}

最佳答案

您的heredoc 需要稍作修改(因为它实际上是Nowdoc!):

    echo <<<EX
    <p>Game: {$data['game_name']}<br/>
    the owner of the game is {$data['game_owner']}
    </p>
    EX;
  • Heredoc 标识符(与 nowdoc 不同)不能被引用。 'EX' 需要变成 EX

    您将 Nowdoc 与 heredoc 混淆了。

  • 字符串中的复杂数据类型必须用 {} 包围,才能将它们解析为变量。例如,$data['game_name'] 应该是 {$data['game_name']}

  • 在过时的 PHP 版本(PHP 7.3 之前)中,heredoc 终止符 不得 有任何前面的空格。来自文档:

    The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line.

您在这里混淆了heredoc 和nowdoc。您想使用 heredocnot Nowdoc,因为您的字符串中有变量。 Heredocs 是“扩展的”双引号字符串,而 nowdocs 更类似于单引号字符串,因为变量不在 nowdoc 字符串中解析,而是在 heredoc 中。

  • 更多关于 heredoc here .
  • 更多关于 Nowdoc here .

请仔细阅读这些文档。

关于php - 在 PHP 的 heredoc 中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11274354/

相关文章:

ruby - 在(双引号)heredoc 中使用 `gsub` 不起作用

php - 您如何在PHP中解析和处理HTML/XML?

php - 有没有办法选择字符串中以空格分隔的第一个单词/字符组合?

Mysql 使用 SELECT CASE 的结果存储变量

Python-我可以使用变量名作为列表中的元素吗?

bash - 禁用 shell 解析的 here-document

php - 正则表达式 PHP 试图剖析一个字符串

PHP.INI 文件路径似乎无法正常工作

ruby-on-rails - 如何将 rails 变量设置为等于 Javascript 变量?

php - 在 PHP 中使用 heredoc 有什么好处?