What is the advantage of using heredoc in PHP?
The heredoc syntax is much cleaner to me and it is really useful for multi-line strings and avoiding quoting issues. Back in the day I used to use them to construct SQL queries:
$sql = <<<SQL
select *
from $tablename
where id in [$order_ids_list]
and product_name = "widgets"
SQL;
To me this has a lower probability of introducing a syntax error than using quotes:
$sql = "
select *
from $tablename
where id in [$order_ids_list]
and product_name = \"widgets\"
";
Another point is to avoid escaping double quotes in your string:
$x = "The point of the \"argument" was to illustrate the use of here documents";
The problem with the above is the syntax error (the missing escaped quote) I just introduced as opposed to here document syntax:
$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;
It is a bit of style, but I use the following as rules for single, double and here documents for defining strings:
- Single quotes are used when the string is a constant like
'no variables here'
- Double quotes when I can put the string on a single line and require variable interpolation or an embedded single quote
"Today is ${user}'s birthday"
- Here documents for multi-line strings that require formatting and variable interpolation.
Advantages / inconveniences of heredoc vs nowdoc in php
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
In other words:
$foo = 'bar';
$here = <<<HERE
I'm here, $foo !
HERE;
$now = <<<'NOW'
I'm now, $foo !
NOW;
$here
is "I'm here, bar !", while $now
is "I'm now, $foo !".
If you don't need variable interpolation but need special characters like $
inside your string, Nowdocs are easier to use. That's all.
In PHP, what does represent?
That's heredoc syntax. You start a heredoc string by putting <<<
plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.
Example:
echo <<<HEREDOC
This is a heredoc string.
Newlines and everything else is preserved.
HEREDOC;
Calling PHP functions within HEREDOC strings
I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages
- No option for WYSIWYG
- No code completion for HTML from IDEs
- Output (HTML) locked to logic files
- You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping
Get a basic template engine, or just use PHP with includes - it's why the language has the <?php
and ?>
delimiters.
template_file.php
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo getPageContent(); ?>
</body>
index.php
<?php
$page_title = "This is a simple demo";
function getPageContent() {
return '<p>Hello World!</p>';
}
include('template_file.php');
define and heredoc
taken from the documentation regarding strings
DEFINE('PREFIX','/holiday');
$const = PREFIX;
echo <<<EOD
<img src="{$const}/images/hello.png" />
EOD;
Is heredoc slower than escaped echo in PHP?
If it's PHP, then guaranteed there are other more important things worth optimizing . i wouldn't sweat HEREDOC sttrings ..
Replacement of the Heredoc syntax
Just use a string.
$features .= "<li> $feature </li>";
Heredoc has the advantage that you don't have to worry about escaping quotes inside the value, so it's very useful for long blocks of HTML.
Disadvantages of using EOF?
Heredocs are wonderful if you're building HTML and need to embed variables.
They honor the linebreaks/spacing you embed within them (even if the browser doesn't display that) so it's MUCH easier to build nicely formatted HTML, and also relieve you of the need to escape quotes while building the strings:
e.g. compare
print("<div class=\"this\">\n\tblah blah\n\t\t<span class=\"that\">blah</span>\n</div>");
v.s.
echo <<<EOL
<div class="this">
blah blah
<span class="that"</span>
</div>
EOL;
They can also be used in concatenation operations, eg.
$x = "hello";
$x .= <<<EOL
there, how
EOL
$x .= <<<EOL
are you?
EOL;
will eventually give $x the value hello there, how are you?
. Basically consider the heredoc syntax to be a VERY fancy version of double-quoted strings, with none of the drawbacks. The only restriction is that the heredoc's sentinal value must be on a line by itself, so there's no way to make a "one line" heredoc.
conditional statements inside php heredocs syntax?
Do you want to have conditional statements in heredoc or do you wonder why your code does not work? Because currently you have no conditional statement inside heredoc, but it is not possible anyway.
If you wonder why your code does not work:
This is not related to heredoc, it is because the entire $reply
string is enclosed in single quotes, where variable parsing is not supported. Use string concatenation:
$reply ='<a class ="reply" href="viewtopic.php?replyto=@' . $username . '.&status_id=$id&reply_name=' . $username . '"> reply </a>'
I hope you are doing more with heredoc in your real code, otherwise return $reply
would be easier ;) (and you are missing brackets).
Related Topics
How to Make Asynchronous Http Requests in PHP
How to Maintain a "Version For the Server" - With Only Config Files Changed, in Git
Pdo Prepared Inserts Multiple Rows in Single Query
Detect Encoding and Make Everything Utf-8
How to Extract Img Src, Title and Alt from HTML Using PHP
How to Convert an Array to Object in PHP
What Are the Best PHP Input Sanitizing Functions
Parse Xml With Namespace Using Simplexml
In_Array() and Multidimensional Array
Convert from MySQL Datetime to Another Format With PHP
How to Use PHP Serialize() and Unserialize()
How to Get File_Get_Contents() to Work With Https
PHP Does Not Display Error Messages