Heredocs and Nowdocs in PHP

A here document (also called a here-document, a heredoc, a here-string or a here-script) is a way of specifying a string literal in command line shells including all the Unix shells (sh, csh, ksh, Bash and zsh) and the Windows PowerShell and in programming or scripting languages such as Perl, PHP, Python and Ruby. It preserves the line breaks and other whitespace (including indentation) in the text. Some languages allow variable substitution and command substitution inside the string.

The general syntax is << followed by a delimiting identifier, followed, starting on the next line, by the text to be quoted, and then closed by the same identifier on its own line. Under the Unix shells, here documents are generally used as a way of providing input to commands.

from Wikipedia

Example 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 foo()
{
$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;
?>

NowDocs

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<‘EOT’. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

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

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

function foo()
{
$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 not print a capital ‘A’: \x41
EOT;
?>

from PHP.net

Related Posts:

  • No Related Posts
This entry was posted in Tech Tips, Web Development and tagged . Bookmark the permalink.

Leave a Reply

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