dongling0519 2014-11-29 15:57
浏览 96
已采纳

如何在PHP Heredoc中转义变量名?

I have a variable $foo with some id in it and I want to use it in Heredoc string in PHP like this:

$text = <<<TEXT
  <div id="$foo_bar"></div>
TEXT;

Obvious problem is that PHP parses variable in Heredoc as $foo_bar which of course, doesn't exist. What I want is to parse $foo variable and "_bar" should be treated as regular text.

Is it possible to use some kind of escape character or it can't be achieved ?

P.S.: Yes, I know I can use quoted string instead of Heredoc, but I must use Heredoc (I have a ton of text and code in it with quotes, etc).

  • 写回答

2条回答 默认 最新

  • dpzjl68484 2014-11-29 15:58
    关注

    Put curly braces around the variable, just like in a quoted string.

    $text = <<<TEXT
      <div id="{$foo}_bar"></div>
    TEXT;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?