What is the advantage of using Heredoc in PHP ?

在PHP中使用Heredoc有什么好处,并且你能展示一个例子吗?


The here doc 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";

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.

  • Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDE's or text editors will use the proper syntax highlighting.

    A VERY common example: echoing out HTML from within PHP:

    $html = <<<HTML
      <div class='something'>
        <ul class='mylist'>
          <li>$something</li>
          <li>$whatever</li>
          <li>$testing123</li>
        </ul>
      </div>
    HTML;
    
    // sometime later
    echo $html;
    

    Easy to read. Easy to maintain.

    The alternative is echoing quoted strings, which end up containing escaped quotes and IDEs aren't going to highlight the syntax for that language, which leads to poor readability and more difficulty in maintenance.

    Updated answer for Your Common Sense

    Of course you wouldn't want to see an SQL query highlighted as HTML. To use other languages, simply change the language in the syntax:

    $sql = <<<SQL
           SELECT * FROM table
    SQL;
    

    Some IDEs hightlight the code in heredoc strings automatically - which makes using heredoc for xml or html visually appealing.

    I personally like it for longer parts of ie XML since I don't have to care about quoting quote characters and can simply paste the XML.

    链接地址: http://www.djcxy.com/p/10020.html

    上一篇: 平等?,eql ?, ===和==有什么区别?

    下一篇: 在PHP中使用Heredoc有什么好处?