问题描述
我想知道为什么我无法在Heredoc中执行类似{number_format($row['my_number'])}
的操作.有什么办法可以解决这个问题,而不必求助于下面的$myNumber
这样的变量?
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?
查看了 http://www.php .net/manual/zh-CN/language.types.string.php#language.types.string.syntax.nowdoc ,但一无所获.
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;
推荐答案
您可以使用{$
变量表达式在HEREDOC字符串中执行函数.但是,您需要预先为函数名称定义一个变量:
You can execute functions in a HEREDOC string by using {$
variable expressions. You however need to define a variable for the function name beforehand:
$number_format = "number_format";
$table .= <<<EOT
<tr>
<td>{$row['my_number']}</td> // WORKS
<td>$myNumber</td> // WORKS
<td>{$number_format($row['my_number'])}</td> // DOES NOT WORK!
</tr>
因此,这种方式打破了HEREDOC简洁的目的.
So this kind of defeats the HEREDOCs purpose of terseness.
出于可读性考虑,为此目的定义一个通用的/无效的函数名称(例如$expr = "htmlentities";
)可能会更加有用.然后,您可以在heredoc或双引号中使用几乎所有复杂的表达式和所有全局函数:
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:
" <td> {$expr(number_format($num + 7) . ':')} </td> "
我认为{$expr(
对于遇到这种构造的任何人来说都更加明显. (否则,这只是一个奇怪的解决方法.)
And I think {$expr(
is just more obvious to anyone who comes across such a construct. (Otherwise it's just an odd workaround.)
这篇关于格式化Heredoc中的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!