Heredoc Comments

Well, I did it again. I had to look up something that I thought I already knew, but used rarely. What I discovered was there was very little information on the web, or in books about heredoc comments. I even had trouble coming up with the name. Thus this article.

Heredoc comments are used when you want to comment out large blocks of text in PHP. When would you use them, you say, or what's wrong with using /* ... */ for long comments?

I was trying to embed a large block of CSS styling into a method of a class. That way I could call the method in the constructor and only embed the styling once when calling the various class methods of the instantiated class. If that was all goobly gook to you, let's just say it saved me having to re-embed the CSS styling every time I called a method in the class.

Let's take a look, here's my styling in compact CSS form:

The CSS styling

Now here's the method that I ended up with using a heredoc

The CSS styling with Heredoc comment tags

Notice the CSS inline comments can still be used in the heredoc comments.

The key to these heredoc comments is the "CSSINSERT" tag, which can be any word you want to make up. The trick is in how you embed the tags in your code. Here are the syntax rules.

  • The actual tag, whatever word you use, at the start and the end must be identical.

  • The start of the tag must be prefaced by three left angle brackets, like so:

    Start of Heredoc with 3 left angle brackets and a word


  • The ending tripped me up at first, and is easy to mess up. The end "CSSINSERT" must be at the start of the line, no spaces allowed, or it won't work. Also the ending semicolon must butt up against the end of the tag, or you'll get a syntax error, and it won't work. Here's the example:

    End tag, no spaces, semicolon against the tag

Think of the heredoc tags as if they were double quotes. Variables and escape sequences are parsed, just as with double quotes.

What about the /* ... */ part of the question? If I use this method PHP ignores the text between the /* */ and I couldn't echo the styling out.


Heredoc Comments — 2 Comments

  1. You have excellent articles, very well thought out and comprehensive. Please change your code extract formats; green on black makes for hard reading, and not at all copyable code (which many users would love to use!). Good job overall!

    • The green on black is what I use in my editor. One of the hard things to reproduce in a blog article is actual code, especially if you mix languages, so occasionally out of frustration, you’ll see the green on black image file, which of course, you cannot copy. We’ll try to keep those to a minimum and only use the green on black when needed, so the code displays properly. Thanks for the feedback Xeno.