This is some PHP code for rendering an HTML anchor element. Why does this:
$archives .= " <a href='" . get_year_link($archPost->year) . "'
title='Click to go to full listing for " . $archPost->year . "' target='_blank'>[List^]</a>";
work exactly like this:
$archives .= " <a href='" . get_year_link($archPost->year) . "'
title='Click to go to full listing for $archPost->year' target='_blank'>[List^]</a>";
Coming from C/C# and such, I have a preference for the first variant, because I think that one cannot just dump variables smack-dab in the middle of the string. Apparently PHP has no problem with this. Why not?
This is called string interpolation, and it is available in C# as well.
Personally, I find using string interpolation to be bad practice. It makes code hard to read in your IDE, and can lead to misinterpretation of strings. (Maybe you wanted that dollar sign to mean a dollar sign, but because you used double quotes "
instead of single quotes '
, you now have a bug.) I concatenate instead:
$var = 'something' . $somethingElse;
If you're using echo
, it is more performant to echo a list, rather than concatenate:
echo 'something', $somethingElse;
The other issue, at least as used in your example, is that you are dumping data directly into the context of HTML with no escaping done. If your output contained reserved entities, you would be generating invalid ambiguous HTML. This can even lead to security issues depending on the context used, such as XSS problems. You want to use htmlspecialchars()
around any arbitrary data used in HTML. (Or, use a template engine that does this for you.)