PHP - String Heredoc Nowdoc

Introduction

You can use your own delimiters in two ways: heredoc syntax and nowdoc syntax.

Heredoc is the equivalent of using double quotes:

  • variable names are replaced with variable values, and
  • you can use escape sequences to represent special characters.

Nowdoc works in the same way as single quotes: no variable substitution or escaping takes place; the string is used entirely as-is.

Heredoc

Heredoc syntax works like this:

$myString =  <<< DELIMITER
(insert string here)
DELIMITER;

DELIMITER is the string of text you want to use as a delimiter.

It must contain just letters, numbers, and underscores, and must start with a letter or underscore.

Traditionally, heredoc delimiters are written in uppercase, like constants.

Nowdoc

Nowdoc syntax is similar; the only difference is that the delimiter is enclosed within single quotes:

$myString =  <<<'DELIMITER'
(insert string here)
DELIMITER;

Here's an example of heredoc syntax in action:

Demo

<?php
$religion ='hi';//  w w  w  . j  a  v  a2 s.  c  o m

$myString =  <<< END_TEXT
"' $religion,'hi'test
test!'"
END_TEXT;

echo " $myString";
?>

Result

Here's the same example using nowdoc syntax instead:

Demo

<?php

$religion ='hi';// ww  w . j a  v a  2  s .co m

$myString =  <<<'END_TEXT'
"'$religion,'test' test
test!'"
END_TEXT;

echo " $myString";
?>

Result