does anybody use PHP heredoc?

decibel.places's picture

He has: 1,494 posts

Joined: Jun 2008

Looking over the Tizag tutorial I read about heredoc string syntax:

$my_string = <<<TEST
Tizag.com
Webmaster Tutorials
Unlock your potential!
TEST;

I have never seen this syntax used - does anybody use it?

What are the advantages over quotes?

I guess you can use double and single quotes with out escaping, right?

So?

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but escape codes can still be used.

It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon. That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

I suppose the advantage is you can quote text and HTML easier within PHP.
ALthough from a few benchmarks I see that it's slower than double quotes. I suppose it depends on what data you are using. Variables or just plain text etc.

for me double or single quotes (depending on data) is just far to convenient to start using another method with no great advantage, but some drawbacks.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.