我是 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。您想使用 heredoc 和 not Nowdoc,因为您的字符串中有变量。 Heredocs 是“扩展的”双引号字符串,而 nowdocs 更类似于单引号字符串,因为变量不在 nowdoc 字符串中解析,而是在 heredoc 中。
请仔细阅读这些文档。
关于php - 在 PHP 的 heredoc 中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11274354/