Monday, 5 August 2013

Is there a reason to use Heredoc in PHP?

Here docs to me are 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\"
";
The here doc syntax is much cleaner to me.
[EDIT - to respond to comments below]
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.


note :

     you should not provide a space between the <<< and the identifier. As specified in the PHP documentation:
(...) the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

No comments:

Post a Comment