Heredoc Syntax in PHP

Heredoc syntax offers a convenient means for outputting large amounts of text. Rather than delimiting strings with double or single quotes, two identical identifiers are employed. An example follows:

$website = "";
echo <<<EXCERPT
<p>Rome's central train station, known as <a href = "$website">Roma Termini</a>,
was built in 1867. Because it had fallen into severe disrepair in the late 20th
century, the government knew that considerable resources were required to
rehabilitate the station prior to the 50-year <i>Giubileo</i>.</p>


Several points are worth noting regarding this example:
• The opening and closing identifiers, in the case of this example, EXCERPT, must be identical. You can choose any identifier you please, but they must exactly match.
The only constraint is that the identifier must consist of solely alphanumeric characters and underscores and must not begin with a digit or an underscore.
• The opening identifier must be preceded with three left-angle brackets, <<<.
• Heredoc syntax follows the same parsing rules as strings enclosed in double
quotes. That is, both variables and escape sequences are parsed. The only
difference is that double quotes do not need to be escaped.
• The closing identifier must begin at the very beginning of a line. It cannot be
preceded with spaces or any other extraneous character. This is a commonly
recurring point of confusion among users, so take special care to make sure
your heredoc string conforms to this annoying requirement. Furthermore, the
presence of any spaces following the opening or closing identifier will produce
a syntax error.
Heredoc syntax is particularly useful when you need to manipulate a substantial amount of material but do not want to put up with the hassle of escaping quotes.


Thanks for Reading


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s