格式化 Heredoc 内的数组值
我想知道为什么我不能在 Heredoc 中执行类似 {number_format($row['my_number'])}
的操作。有什么办法可以解决这个问题,而不必求助于定义像下面的 $myNumber
这样的变量吗?
查看http://www.php.net/ Manual/en/language.types.string.php#language.types.string.syntax.nowdoc 但什么也没找到。
代码
foreach ($dbh -> query($sql) as $row):
$myNumber = number_format($row['my_number']);
$table .= <<<EOT
<tr>
<td>{$row['my_number']}</td> // WORKS
<td>$myNumber</td> // WORKS
<td>{number_format($row['my_number'])}</td> // DOES NOT WORK!
</tr>
EOT;
endforeach;
I was wondering why I can't do something like {number_format($row['my_number'])}
inside a Heredoc. Is there any way around this without having to resort to defining a variable like $myNumber
below?
Looked at http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc but found nothing.
CODE
foreach ($dbh -> query($sql) as $row):
$myNumber = number_format($row['my_number']);
$table .= <<<EOT
<tr>
<td>{$row['my_number']}</td> // WORKS
<td>$myNumber</td> // WORKS
<td>{number_format($row['my_number'])}</td> // DOES NOT WORK!
</tr>
EOT;
endforeach;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
{$
变量表达式执行 HEREDOC 字符串中的函数。然而,您需要预先为函数名称定义一个变量:因此这种方式违背了 HEREDOC 的简洁目的。
为了提高可读性,为此目的定义一个通用/无效函数名称(例如
$expr = "htmlentities";
)可能会更有帮助。然后,您可以在定界符或双引号中使用几乎任何复杂的表达式和所有全局函数:而且我认为
{$expr(
对于遇到这种构造的任何人来说都更明显。(否则这只是一个奇怪的事情)解决方法。)You can execute functions in a HEREDOC string by using
{$
variable expressions. You however need to define a variable for the function name beforehand:So this kind of defeats the HEREDOCs purpose of terseness.
For readability it might be even more helpful to define a generic/void function name like
$expr = "htmlentities";
for this purpose. Then you can utilize almost any complex expression and all global functions in heredoc or doublequotes:And I think
{$expr(
is just more obvious to anyone who comes across such a construct. (Otherwise it's just an odd workaround.)