I would like to store the following code inside a HEREDOC variable:
<?php
$var = 'test';
echo $var;
?>
like this:
$hered = <<<HERED
<?php
$var = 'test';
echo $var;
?>
HERED;
The problem is that HEREDOC works like double quotes, ""
- that means each dollar sign ($
) has to be replaced with \$
...
Is there a way to use HEREDOC without performing such an operation?
Yes, there is. Check out the nowdoc syntax:
$hello = 'hey';
$echo <<<'EOS'
$hello world!
EOS;
//Output: $hello world
It can be done using \
:
echo <<<HEREDOC
<?php
\$var = 'test';
echo \$var;
?>
HEREDOC;
I know there's now doc, but for example my current use case needs heredoc, because some dollars need to be escaped and some not:
$variableNotToEscape = 'this should be output';
echo <<<HEREDOC
$variableNotToEscape
\$variableNotToEscape
HEREDOC;
Which returns
this should be output
$variableNotToEscape
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With