Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pro and cons using Heredoc Notation in your PHP?

Tags:

syntax

php

I've never seen something like this before. So, it's confusing me for a while. But now I understand and use it sometimes. So, after brief experience, can anybody tell me what is the pro and cons using Heredoc Notation in your PHP?

$stringval = <<<MYHEREDOC

   just creating variable here. nothing more.

MYHEREDOC;

Personally, how do you use this PHP feature? Is it a bad way of coding or good way?

like image 498
justjoe Avatar asked Mar 21 '10 13:03

justjoe


1 Answers

99% of the time I use it, it's for SQL queries eg:

$sql = <<<END
SELECT *
FROM sometable
WHERE value > 100
ORDER BY name
END;

I find it easier to spot such queries in the source code and copy and paste them into something to run them. Your mileage may vary. Note: you can do multi-line with normal strings. I tend to avoid this however as the first line is indented differently to the rest.

The biggest "pro" as far as I'm concerned is that you don't need to escape quotes. That's particularly an issue with markup. Decide for yourself which is easier to read. Assuming:

$name = 'foo';
$type = 'text';
$value = 'Default value';

Version 1: single quotes

$html = '<input type="' . $type . ' name="' . $name . '" value="' . $value . '">';

Version 2: double quotes

$html = "<input type=\"$type\" name=\"$name\" value=\"$value\">";

Version 3: heredoc

$html = <<<END
<input type="$type" name="$name" value="$value">
END;

Note: in version 2 you can of course use single quotes for attribute values to solve the escaping problem but the point is you have to worry about things like this. Personally I don't like to mix attribute quote types in markup either.

like image 135
cletus Avatar answered Sep 24 '22 21:09

cletus