Formatting an array value inside a Heredoc

浪尽此生 提交于 2019-12-03 10:07:18

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>

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:

    "   <td>  {$expr(number_format($num + 7) . ':')}  </td>  "

And I think {$expr( is just more obvious to anyone who comes across such a construct. (Otherwise it's just an odd workaround.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!