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:
Now here's the method that I ended up with using a heredoc
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:
- 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:
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.