0

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).

Frodik
  • 14,986
  • 23
  • 90
  • 141

2 Answers2

2

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

$text = <<<TEXT
  <div id="{$foo}_bar"></div>
TEXT;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    Just as an aside, note that you could also open the curlies after the `$`: `
    `. It's not idiomatic PHP, but it's in keeping with the way it works in the shell and Perl.
    – Mark Reed Nov 29 '14 at 16:04
  • I don't even think it's documented in the PHP manual. I guess it's just there for shell/Perl compatibility, but I wouldn't recommend it. – Barmar Nov 29 '14 at 16:10
  • @Barmar Sure [is documented](http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex) – Alexandru Guzinschi Nov 29 '14 at 17:42
  • @AlexandruGuzinschi It's shown in the examples, but the text of the documentation never mentions it. It only describes `{$var}`. – Barmar Nov 30 '14 at 14:55
1

Use this code instead to force using $foo.

$text = <<<TEXT
  <div id="{$foo}_bar"></div>
TEXT;

Curly brackets force the contents to be a variable.

Alternatively, you could attach "_bar" before the HEREDOC.

$foo = $foo . "_bar";
$text = <<<TEXT
  <div id="$foo"></div>
TEXT;
Nerixel
  • 427
  • 3
  • 9
  • I suggest you use a new variable in the second example, rather than reusing `$foo`, e.g. `$foobar = $foo . "_bar";` – Barmar Nov 29 '14 at 16:00
  • That can be good, but unless you're going to have another use for `$foo` there's no reason, just takes up more memory. – Nerixel Nov 29 '14 at 16:01