# Patch to add "single-quote" heredocs

- Thread: https://externals.io/message/30940
- Original archive: https://news-web.php.net/php.internals/30940
- Started by Gwynne Raskind on 2007-07-14T21:43:28+00:00
- Messages: 1
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #30940 — Gwynne Raskind — 2007-07-14T21:43:28+00:00

URL: https://externals.io/message/30940#30940

So I was using create_function() in various ways, and I said to  
myself, "this would look SO much better if I could use a heredoc that  
acted like a single-quoted string". Then I said to myself, "Wait. I  
know the PHP internals. Why don't I build a new syntax into the  
language?" The result was a small modification of the heredoc syntax  
that I call "nowdoc", and it looks like this:

<?php
$n = 1;

$a = <<<ENDOFHERE
I see $n.
ENDOFHERE;

$b = <<<~ENDOFNOW
I see $n.
ENDOFNOW;

print "{$a}\n{$b}\n";

?>

And the output is:

I see 1.
I see $n.

The b modifier is fully supported; a nowdoc acts exactly like a  
single-quoted string, save that you can embed single quotes into it.  
I wrote the patch for HEAD, backported it to PHP_5_2 (both fully up- 
to-date as of this message), and wrote a set of regression tests. The  
patch breaks none of the existing regression tests, and has no BC or  
SC breaks whatsoever, as far as I can tell. The patch can be found at  
<http://phpdoc.gwynne.dyndns.org/nowdocs.tar.gz>. I hope to see it  
included in PHP 6 and 5.3, maybe even 5.2.4 or 5.2.5 since existing  
scripts will continue to work without modification. <<<~ was a parse  
error before, so anyone who used it was doing something wrong anyway.

Side note: I implemented nowdocs in the parser by sharing the heredoc  
code and passing $ and {$ through unmodified instead of replaced. I  
don't understand the way the HEREDOC_CHARS regexps work well enough  
to write a simpler matching rule for the newdocs, but it's clear that  
the patch could be optimized if only I knew how, since the entire  
content can be parsed by a single call to zend_scan_[unicode|binary_] 
escape_string() rather than having to be parsed for replacements. I  
may look into this later, but for the moment I wanted to get what's  
working out there in the commmunity.

-- Gwynne, Daughter of the Code
"This whole world is an asylum for the incurable."
