CS 601 – PHP Multiline Strings

During the course of my project, I had many instances of needing to write very long strings, often when constructing moderately complex MySQL queries. There are several way to do this. One would be repeated each statements or assignment with .= . Another would be running the echo/assignment over multiple lines by using . at the end of each until the final one (ended with ; ). Example:

$mystr = 'Here is a really long line of text that runs to '.
         'more than one line';

I found a very clean and convenient way is to use PHP’s heredoc syntax. Here’s an example:

$query = <<<EOT
        SELECT * FROM tblOrderItems
        INNER JOIN tblFoodItems
                ON tblFoodItems.intFoodItemID = tblOrderItems.intFoodItemID
        INNER JOIN tblFoodCategories
                ON tblFoodCategories.intFoodCategoryID = tblFoodItems.intFoodCategoryID
        INNER JOIN tblFoodCategoryOrder
                ON tblFoodCategoryOrder.intFoodCategoryID = tblFoodCategories.intFoodCategoryID
        WHERE intOrderID = {$order['intOrderID']}
        ORDER BY tblFoodCategoryOrder.intFoodCategoryOrder, tblFoodItems.vcFoodItemName

There’s a few things to note:

  • The EOT is arbitrary as long as both instances are the same. (I use EOT for “end of text”.)
  • Variables can be included in the string. A simple variable is simply included as $myvar. Here, I use the {} to separate out a “complex” variable. (I didn’t realize this could be done until later on, so for some of my earlier instances, I set it to a simpler variable immediately before the heredoc declaration.)
  • The terminator (here EOT;) MUST be on a line by itself with no leading or trailing whitespace. This cannot be emphasized enough. Leading whitespace is pretty easy to spot, but several times NetBeans added trailing whitespace which wasn’t obvious in and of itself. (NetBeans does color the heredoc string differently, so you will see the “carry over”.) I finally got in the habit of checking.

PHP ≥ 5.3.0 also has the nowdoc syntax. It’s very similar to heredoc except is uses $myvar = <<<‘EOT’ (note the single quotes). The difference is that variables are not expanded akin to standard single quoted strings.

Leave a Reply

Your email address will not be published. Required fields are marked *