📜  heredoc - PHP (1)

📅  最后修改于: 2023-12-03 15:15:30.691000             🧑  作者: Mango

Heredoc in PHP

In PHP, heredoc is a way to create strings that span multiple lines and contain variables without having to use concatenation.

Syntax

The syntax for heredoc is as follows:

$text = <<<EOT
This is a heredoc string.
It can span multiple lines.
Variables can be included like this: $variable
EOT;
Features
  • Heredoc strings start with <<< followed by an identifier (in this case, EOT). The identifier can be any string, as long as it does not appear in the string content.
  • The content of the string starts on the next line and ends with the identifier on a line by itself.
  • Variables can be included in the string by surrounding them with $.
  • The string content is treated as-is, with no need to escape special characters like newline or double quotes.
  • Heredoc strings can be used in place of double-quoted strings where appropriate.
Example
$name = "John Smith";
$title = "Software Developer";
$bio = <<<EOT
Name: $name
Title: $title

John is a software developer with 5 years of experience. He specializes in PHP and JavaScript.

In his free time, John enjoys hiking and playing guitar.
EOT;

echo $bio;

Output:

Name: John Smith
Title: Software Developer

John is a software developer with 5 years of experience. He specializes in PHP and JavaScript.

In his free time, John enjoys hiking and playing guitar.
Conclusion

Heredoc strings can make it easier to create strings that span multiple lines and contain variables. They are particularly useful for long strings with complex formatting.