php
  1. php-heredoc-syntax

PHP Heredoc Syntax

The heredoc syntax is a flexible way to represent strings that contain multiple lines of text. In PHP, the heredoc syntax is denoted by three angle brackets (<<<) followed by an identifier, and then the string itself. The identifier can be any sequence of letters, digits, or underscores, as long as it is not a reserved word in PHP. The identifier must also be followed by a newline character.

Syntax

<<<[identifier]
    string
[identifier];

Example

$variable = <<<EOT
This is a heredoc string.

It can span multiple lines, and can contain any type of character, including quotes ("like this" and 'like this').

The identifier can be any sequence of letters, digits, or underscores, as long as it is not a reserved word in PHP.

Remember to include the semicolon (;) after the identifier.
EOT;

echo $variable;

Output

This is a heredoc string.

It can span multiple lines, and can contain any type of character, including quotes ("like this" and 'like this').

The identifier can be any sequence of letters, digits, or underscores, as long as it is not a reserved word in PHP.

Remember to include the semicolon (;) after the identifier.

Explanation

The heredoc syntax allows us to represent multiline strings without having to use concatenation or escape sequences.

The opening <<< followed by the identifier and a newline is used to indicate the start of the heredoc string. The string itself can contain any type of character, including quotes and special characters.

It's important to note that any variables or expressions in the heredoc string will be evaluated at runtime, so make sure they are properly escaped or wrapped in curly braces if necessary.

When the closing identifier is encountered, the heredoc string will end.

Use

The heredoc syntax can be useful when dealing with large blocks of text, such as HTML code or SQL queries. It can also be used to maintain indentation and readability in code that includes long strings.

Important Points

  • The heredoc string must be terminated by a semicolon and the closing identifier must be followed by a semicolon.
  • The identifier must be a valid PHP identifier that is not a reserved word.
  • Any variables or expressions inside the heredoc string will be evaluated at runtime.

Summary

  • The heredoc syntax is a flexible way to represent multiline strings in PHP.
  • The syntax is denoted by three angle brackets (<<<) followed by an identifier and a newline, and then the string itself.
  • The closing identifier must be followed by a semicolon.
  • Variables and expressions inside the heredoc string will be evaluated at runtime.
  • The heredoc syntax can be useful for maintaining indentation and readability in code that includes long strings.
Published on: