Syntax: Heredoc syntax

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

/* More complex example, with variables. */
class foo
{
    var $foo;
    var $bar;

    function __construct()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
<?php
// Static variables
function foo()
{
    static $bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class properties/constants
class foo
{
    const BAR = <<<FOOBAR
Constant example
FOOBAR;

    public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
  • A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
  • The closing identifier must begin in the first column of the line.
  • Heredoc text behaves just like a double-quoted string, without the double quotes.
  • Quotes in a heredoc do not need to be escaped.
  • Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
Identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Heredoc in arguments

<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>

It is also possible to use the Heredoc syntax to pass data to function arguments.

Syntax: Heredoc syntax — Structure map

Clickable & Draggable!

Syntax: Heredoc syntax — Related pages: