Difference Between Heredoc and Nowdoc in PHP

Introduction

In this article I will explain the difference between Heredoc and Nowdoc in PHP. Heredoc and Nowdoc are two methods for defining a string. A third and fourth way to delimit strings are the Heredoc and Nowdoc; Heredoc processes $variable and special character but Nowdoc does not processes a variable and special characters. First of all I will discuss Heredoc.

Heredoc allows a multi-line string to be easily assigned to variables or echoed. Heredoc text behaves just like a string without the double quotes.

Example

The following is a simple example of Heredoc:

<?php

$Message = 'Hello';

$str = <<<MYExa

$Message Sharad !!!

How r u?

MYExa;

echo $str;

?>

Output

here2.jpg

Example

<?php

class ABC

{

    var $ABC;

    var $bar;

    function ABC()

    {

        $this->ABC = 'ABC';

        $this->bar = array('Bar1', 'Bar2', 'Bar3');

    }

}

$ABC = new ABC();

$name = 'Tom';

echo <<<EOT

My name is "$name". I am printing some $ABC->ABC.

Now, I am printing some {$ABC->bar[1]}.

This should print a capital 'A': \x41

EOT;

?>

Output

here1.jpg

Example

Heredoc in Arguments

<?php

var_dump(array(<<<EOD

ABCabc!

EOD

));

?>

Output

here3.jpg

Example

Using double-quote in Heredoc

<?php

echo <<<"ABCBAR"

Hello MCN!

ABCBAR;

?>

Next, I will discuss Nowdoc. Nowdoc is an identifier with a single quote string and Nowdoc is specified similarly to a Heredoc but no parsing is done inside a Nowdoc.  A Nowdoc is identified with the same "<<<" sequence used for heredoc. When you use Nowdoc then you cannot pass the space character.

Note Nowdoc is supported only PHP 5.3

Example

Heredoc string quoting example

<?php

class ABC

{

    public $ABC;

    public $bar;

 

    function ABC()

    {

        $this->ABC = 'ABC';

        $this->bar = array('Bar1', 'Bar2', 'Bar3');

    }

}

$ABC = new ABC();

$name = 'Tom';

 

echo <<<'EOT'

My name is "$name". I am printing some $ABC->ABC.

Now, I am printing some {$ABC->bar[1]}.

This should not print a capital 'A': \x41

EOT;

?>

Output

nowd1.jpg


Similar Articles