I have inherited a website for which I need to make some changes. As always there are many ways to do things in website development. However, this particular site has me confused. All the html is delivered via heredoc php scripts. However, none do any php processing.
For example (structure only) index.php:
<?php
$html = <<<html
<html>
<head></head>
<body>
{more simple HTML here. No php processing to be done}
</body>
</html>
html;
echo $html;
?>
I understand the php but I can't figure out why they generate the page this way as oppose to simply deliver it without the php variable processing. Before I just assume the person had no idea what they were doing I thought I'd ask. Any ideas?
This is my first post to StackOverflow so feedback on forum etiquette also welcome.
Heredoc PHP syntax is a way to write large bloc of text inside PHP, without the classic single quote, double quotes delimiters. It relies on <<< and a token that will also mark the end of the string.
A heredoc is a way to define a multiline string, while maintaining the original indentation & formatting. You can use a Heredoc to embed snippets of SQL, HTML, or even XML code. A Heredoc starts with <<- , followed by a word that represents the name for the heredoc, then the contents.
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.
Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.
It might be because they intended to use PHP variables within the HEREDOC. Your example doesn't have those, but I would hazard a guess that they are used in places. From there, I would then just imagine HEREDOC used everywhere for consistency.
The reason for the heredocs is probably because you don't have to escape quotes or worry about quotes at all within a heredoc, whereas string literals you have to manage the quotes accordingly.
It is more common though to keep HTML in a separate file or use a template system - generally that would be a better option than heredocs or string literals.
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