Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HEREDOC interfering with code indentation

Tags:

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?

like image 287
Pekka Avatar asked Feb 21 '10 12:02

Pekka


People also ask

What is the purpose of using the heredoc and Newdoc in PHP?

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.

What is a heredoc string?

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.

What is heredoc syntax?

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.

What is here document in PHP?

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.


1 Answers

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();     } } 
like image 175
Jeff Puckett Avatar answered Sep 21 '22 15:09

Jeff Puckett