17
votes

I've been developing with PHP for some years now, and recently came across this code:

<?php
    echo <<<EOB
        <html>
        <head>
            <title>My title</title>
        </head>
        ...
    EOB;
?>

I've never seen this approach to print HTML, which seems to be pretty useful and less prone to some weird variable or double quote syntax error.

I've searched for some official information about this and only found a post of Rasmus talking about this.

What is a detailed explanation about this functionality and what does EOB mean? Maybe end of block?

5
What's weird about this code is it could have just exited PHP mode and accomplished the same thing.jmucchiello

5 Answers

30
votes

This is known as heredoc syntax. The documentation will tell you everything you need to know.

Essentially, however:

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. Also, the 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.

So EOB is just what the author chose as his delimiter, not really sure what it stands for in his case but the identifier can be whatever you want.

6
votes

Just for the sake of completeness, Heredoc in PHP is inherited from Perl, which itself inherited it from the Bourne shell.

3
votes

It´s called heredoc and is described in the manual.

2
votes

The official term is 'here document' I believe, usually shortened to 'heredoc'.

0
votes

This is called heredoc syntax. It lets you treat large blocks of text like a string. It allows for newlines as well. Variables can be inserted into the block of text, just like using the double quotation marks for strings.

A more useful explanation can be found on PHP's own website: http://php.net/manual/en/language.types.string.php