Monday, 24 November 2014

PHP heredoc syntax

PHP heredoc syntax



Heredoc is a robust way to create string in PHP with more lines but without using quotations. Heredoc is rarely used as the day by day usage is more complicated as creating strings with quotes or double quotes. Besides this the not properly used heredoc can lead to problems in your code.
However if you want to use it you can do it in the following way:
Code:
  1. <?php
  2. $str = <<<DEMO
  3. This is a
  4. demo message
  5. with heredoc.
  6. DEMO;
  7.  
  8. echo $str;
  9. ?>
Output:
This is a demo message with heredoc.
As you see the heredoc starts with the <<< operator and an identifier. After it you can type your text in more lines as if it were a double quoted string. It means that you can use variables inside the heredoc. If you are ready with your text you only need to write the identifier again in a new line as follows:
Code:
  1. <?php
  2. $name = "Max";
  3. $str = <<<DEMO
  4. Hello $name! <br/>
  5. This is a
  6. demo message
  7. with heredoc.
  8. DEMO;
  9.  
  10. echo $str;
  11. ?>

0 comments:

Post a Comment