user990788
user990788

Reputation: 223

How can I store PHP code inside a 'heredoc' variable?

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?

Upvotes: 12

Views: 9294

Answers (2)

simPod
simPod

Reputation: 13506

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

Upvotes: 7

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91983

Yes, there is. Check out the nowdoc syntax:

$hello = 'hey';
$echo <<<'EOS'
$hello world!
EOS;
//Output: $hello world

Upvotes: 22

Related Questions