1

Possible Duplicate:
Calling PHP functions within HEREDOC strings

I need to insert the results of functions into the middle of heredoc..

$r = func1();
$s = func2();

echo <<<EOT

line1
$r
$s
line3
EOT;

I am not sure if any better way to write it as I need to evaluate all the functions beforehand which make the code stupid.

Better if have something like..

echo <<<EOT

line1
{func1()}
{func2()}
line3
EOT;

Of course the above code does not work, but just want to show my idea...

Community
  • 1
  • 1
Howard
  • 19,215
  • 35
  • 112
  • 184
  • Your first example is the way to it. {} only evaluates variables. – Lenin Dec 15 '12 at 18:21
  • Check this out, answer to your question: http://stackoverflow.com/questions/104516/calling-php-functions-within-heredoc-strings – sk8terboi87 ツ Dec 15 '12 at 18:22
  • A heredoc string is not a template. The only way I know how this could be done is with an object abusing the `__get()` functionality, but you more likely better of with breaking up the parts, of prefilling the variables. – Wrikken Dec 15 '12 at 18:23

1 Answers1

3

No, there is no better way to do it.

Heredoc string syntax behaves much like double quote string syntax. You can't put a function name as an expression inside of the double quoted string any more than you can a heredoc. So what you're doing is fine and that's how you should be doing it. The only time you can get interpolation inside of string syntax in PHP is if the value is a variable.

For example...

$foo = function() { return 'value'; };
echo <<<SOMEHEREDOC
{$foo()}
SOMEHEREDOC;
// Is the same as
echo "{$foo()}";
// Is the ssame as
$foo = 'strtoupper';
echo "{$foo('hello world')}";

The above code would output

value

value

HELLO WORLD

Community
  • 1
  • 1
Sherif
  • 11,786
  • 3
  • 32
  • 57