-1


So, in Perl and PHP, you can produce a block of text using a number of the "<" symbols:
Perl:

return <<TEXT;
    <a href=$foo>Perl interpolates this properly</a>
TEXT

PHP:

return <<<TEXT
    <a href=$bar>PHP does not interpolate this...</a>
TEXT;

So, my question is, is there a way to (cleanly) do this in PHP like in Perl?
I have tried <?...?> and <?php...?>, but they do the same thing...
Also, this is really a subset of the entire block of text... otherwise I would just build the string.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Thumper
  • 525
  • 1
  • 6
  • 21
  • So, what about it isn't working? What do you mean by "(cleanly)" ? Expected and actual outcome? – mario Jul 20 '12 at 19:35
  • I should have specified, it isn't interpolating "$foo" like it should be. I believe I should put my foot in mouth, though. I believe Frits answered it, and showed me what I was doing incorrectly... I never tried it without the php tags... – Thumper Jul 20 '12 at 19:38
  • PHP heredocs interpolate variables in the doc by default, as if it were a double quoted string. Your posted code should work just fine. – Alex Howansky Jul 20 '12 at 19:38
  • 1
    Enable `error_reporting(E_ALL)`. If `$foo` isn't defined, there is no interpolation to be expected. – mario Jul 20 '12 at 19:39
  • 2
    Maybe it's not interpolating $foo because your PHP example uses $bar... :) – Alex Howansky Jul 20 '12 at 19:40
  • My second reply said I should put my foot in mouth... I have the correct syntax here, but did not in my code... I didn't even notice it until I saw Frits' answer... – Thumper Jul 20 '12 at 20:00
  • Your Perl HERE doc syntax is WRONG. (I can't speak for the PHP syntax). The semicolon is mis-placed. It doesn't belong at the terminating "`TEXT`", it belongs after the opening `TEXT`, as in "`return < – DavidO Jul 20 '12 at 20:01

2 Answers2

3

Yes, it's called heredoc syntax:

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • Obviously he already knew that syntax, as shown by OPs second example. His inquiry was about variables within there. Did you get what specifically his inquiry was about? – mario Jul 20 '12 at 19:37
  • I have no clue what OP means. Maybe he wrote it as bare text file (no enclosing – mario Jul 20 '12 at 19:41
  • Frits, even though you didn't answer my question directly (I had the string block syntax down), looking at the link, I saw that I had not tried just using the variable without any php blocks (without noticing, as my syntax here is correct). I still need to verify it works, and I'll get back to you guys! – Thumper Jul 20 '12 at 20:01
2

PHP Heredocs are treated just like double-quoted strings, so if you intent is the have the value of $bar shown in the final string, this should work.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103