What is php heredoc used for?

With the arrival of PHP 7.3 last month came some interesting changes to the existing heredoc and nowdoc syntaxes. However, not everyone I spoke to even knew that this syntax existed in PHP, so now seems like a good opportunity to take a look at what they are and how to use them.

Strings

In PHP we have several options for specifying a string value. The two most common approaches are to use either single or double quotes. We also have heredoc and nowdoc syntaxes which are useful when we want to define a multiline string.

Before we look at heredoc and nowdoc let’s refresh our memories on single and double quote strings. There are a couple of differences between these two methods.

When we use a double quote string we can use escaped characters like \n which gets interpreted as a new line break and variables will get substitued for their respective values. For example:-

$foo = 'bar';
echo "Hello $foo\nGoodbye!";
// Output:-
// Hello bar
// Goodbye!

Single quoted strings are literal.

  • This means escaped characters do not expand, e.g. '\n' will not result in a new line, the string will literally be a backslash followed by the character n
  • Variables do not get replaced by their respective values

For example.

$foo = 'bar';
echo 'Hello $foo\nGoodbye!';
// Output:- 
// Hello $foo\nGoodbye!

The one exception is you can use \' in a single quoted string if you need to include a single quote in the string value.

So what about the heredoc and nowdoc syntaxes? They provide an alternative way of defining strings in PHP. They are particularly useful when we need to define a string over multiple lines.

They work by defining an identifier that will mark the start and end of the string. The identifier can be any alphanumeric value following the same rules we’d use for variable names. One important thing to note with the identifier is that as of PHP 7.3 you need to make sure that it does not appear within the string itself.

Here’s an example of a heredoc.

echo 

Chủ Đề