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?
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';
$html = '<input type="' . $type . ' name="' . $name . '" value="' . $value . '">';
$html = "<input type=\"$type\" name=\"$name\" value=\"$value\">";
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With