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).
Put curly braces around the variable, just like in a quoted string.
$text = <<<TEXT
<div id="{$foo}_bar"></div>
TEXT;
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;