SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Aug 2010
    Posts
    193
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    trying to understand heredoc

    I read that heredoc is for long strings of text specifically multi lines. So are we talking quantity of text or formatting?

    One example I read is that someone used to use heredoc for writing out sql strings in php, so they could read the query easier.

    But I write queries all the time on multiple lines without a problem, without any form of concatenating:

    $sql = "SELECT
    *
    FROM
    my_table";

    I just don't understand if heredoc is for, say, a paragraph of text, or multiple lines ( formatting wise ), that need to echo out on the page in multiple lines.

    Thanks

  2. #2
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    Using heredoc eliminates the need for the escaping of special characters, unlike with strings. So, if you have a large block of text or code that you want displayed somewhere without going through the trouble of escaping everything, you have that option.
    Visit The Blog | Follow On Twitter
    301tool 1.1.5 - URL redirector & shortener (PHP/MySQL)
    Can be hosted on and utilize your own domain

  3. #3
    SitePoint Enthusiast
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    88
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    heredocs is really great for writing out large blocks of html code, mixed in with some php vars. No php start/end tags, no writing echo statements with quotes and semis. Just start the heredocs block, write your html with perhaps a php var in the middle to display some dynamic content and then close the heredocs and echo that variable (that's how I do it). So much easier and much more readable!

  4. #4
    SitePoint Evangelist
    Join Date
    Oct 2005
    Location
    Michigan, USA
    Posts
    434
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    It's a good candidate for when you have a string with many quotes. You shouldn't have to escape anything but $
    PHP Code:
    $str = <<<EndMe
    On the seat back of the bench on which Shelly O'riley sat was the plaque inscribed "In Loving Memory" 
    but she neither felt loved nor wished to have any memory of the previous forty-eight hours.

    "M'am. Excuse me! M'am?" the young undertaker's assistant came calling down the lane.
    EndMe; 
    Though I suppose that example could really use Nowdoc since there aren't any variables used in it.
    - Robert


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •