The PHP “heredoc” Syntax

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.

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.

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.


One Response

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

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

Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,


If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the