Formatting an array value inside a Heredoc

后端 未结 1 684
广开言路
广开言路 2021-02-12 12:06

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 defin

1条回答
  •  天命终不由人
    2021-02-12 12:35

    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 .= <<
          {$row['my_number']} // WORKS
          $myNumber // WORKS
          {$number_format($row['my_number'])} // DOES NOT WORK!
          
    

    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:

        "     {$expr(number_format($num + 7) . ':')}    "
    

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

    0 讨论(0)
提交回复
热议问题