The PHP “heredoc” Syntax

Last Updated on: September 15, 2022

An excellent alternative method to assigning string variables is to use the heredoc syntax.

If you are assigning long strings of text with characters that need escaping, try this:

$string = <<<EOT
 This text has 'quote' "marks" that don't need escaping and
 new lines will be saved.
EOT;

To me, it looks a bit messy at first, but it does make large chunks of text more readable in your code. Consider this alternative to the above:

$string = "This text as 'quote' /"marks/" that do need /"lots/ of escaping and\nnew lines need representing";

heredoc syntax will also parse variables, so this is perfectly valid:

$monkeyName = 'Fred';

$string = <<<EOT
 I have a cute pet monkey called $monkeyName.
EOT;

echo $string; // I have a cute pet monkey called Fred.

Give the heredoc syntax a try… it’s not for everyone, but it does have it’s uses.


Get notified of new posts:


Similar Posts

One Comment

  1. The code in the example doesn’t work for me. Try this instead. 🙂

    $longString = <<<EOT
    Here’s a better version that works!
    EOT;

Leave a Reply

Your email address will not be published. Required fields are marked *