I like the HEREDOC syntax, e.g. for edge cases of generated HTML that are not worth putting into a template.
The only thing that annoys me about it, though, is that the content, and the closing marker of a heredoc string adheres to the first column. This screws up nested code layouts:
class myclass { function __construct() { $a = some_code(); $b = some_more_code(); $x = <<<EOT line1 line2 line3 line4 EOT; $c = even_more_code(); $b = still_more_code(); ... ... ...
you see what I mean.
Now this is probably not solvable using normal HEREDOC. Has anybody worked around this? My dream would be to have HEREDOC syntax with automatic indentation. But I guess this is not possible without writing some pre-compiler for the source files.
Am I correct?
Heredoc and nowdoc provide useful alternatives to defining strings in PHP to the more widely used quoted string syntax. They are especially useful when we need to define a string that spans multiple lines (new lines are also interpreted when used in quoted strings) and where use of whitespace is important.
In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file.
The heredoc syntax is a way to declare a string variable. The heredoc syntax takes at least three lines of your code and uses the special character <<< at the beginning.
Heredoc is one of the ways to store or print a block of text in PHP. The data stored in the heredoc variable is more readable and error-free than other variables for using indentation and newline.
Thank goodness this feature has finally landed in php 7.3 via RFC: Flexible Heredoc and Nowdoc Syntaxes
So now your example can cleanly be written as:
class myclass { function __construct() { $a = some_code(); $b = some_more_code(); $x = <<<EOT line1 line2 line3 line4 EOT; $c = even_more_code(); $b = still_more_code(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With