Any advantage in using php heredoc strings rather than adding slashes before quotes? [closed]

StackOverflow https://stackoverflow.com/questions/17254838

  •  01-06-2022
  •  | 
  •  

Pregunta

I. Are there any advantages in using heredoc format rather than using ' and "?

The only obvious one, is that when we use heredoc format, we do not need the \' or \".

Any other reason to use heredoc? Maybe from the aspect of processing speed and so...

Note: I'm not thinking of readability or other personal preferences.

II. Are variables like $var processes in a string that has heredoc format?

¿Fue útil?

Solución

  1. There are no advantages to using heredoc. Except for newlines (you didn't mention this).
  2. Variables will expand as they would in double quoted strings.

PHP will not allow heredoc to be used in the initialization of class properties, so you could say that's an disadvantage as well (Since php5.3 however, this is only true for variables within the heredoc).

Nowdoc is to single quote, as Heredoc is to double quotes. (Nowdoc will not expand variables).

Otros consejos

I use heredocs a lot in bash programming - as a quick and dirty template for generating files. Heredocs are also easier to include in a source file being merged from multiple other files (it is easier to distribute data and code in only one file).

IMHO it is a useful technique for improving readability of the data being included inside the source file. Heredocs were also used to create self-extracting scripts much easier then creating self-extracting archives.

I guess in PHP they have similar (and marginal) usage. For example: I imagine it is easier and cleaner to embed some Javascript code in a heredoc then in a quoted string - imagine some complex regex in javascript inside a PHP file and all the backslashes escaping.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top