Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 427
user990788 Avatar asked Oct 18 '11 08:10

user990788


2 Answers

Yes, there is. Check out the nowdoc syntax:

$hello = 'hey';
$echo <<<'EOS'
$hello world!
EOS;
//Output: $hello world
like image 187
Emil Vikström Avatar answered Sep 27 '22 20:09

Emil Vikström


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
like image 45
simPod Avatar answered Sep 27 '22 20:09

simPod