Quotes - Single and Double
|Topics on this page:
In the above, using double quotes, the variable $something is evaluated within the quotes and the result isn't what is expected: the variable is evaluated to Oh something. Variables, but not functions or constants, are evaluated even when enclosed in double quotes.
When single quotes are used, as above, the variable isn't evaluated and is printed on the screen literally as $something.
The backslash character (\) can be used to escape quotes and variables. The next example repeats the idea that things are evaluated within double quotes:
So nothing new here, just a reminder. Next we use the backslash to escape the variable $something and also the double quotes around "is":
The program doesn't crash on finding more double quotes, but understands that these are just to emphasise "is". And the program does not explode $something, but prints it literally, because it is escaped.
Consider the following:
In order to show a backslash, we need to double it "\\". In the above, we also need a backslash to escape. Therefore we have three backslashes before the double quotes which we want to escape, and also three before the first occurrence of $something. Therefore, none of "My answer \\\"is\\\" \\\$something=" is evaluated and so we see the code. That is, we see "My answer \"is\" \$something=". The next part is the code we want to run, which results in "My answer "is" $something "
Another peculiarity about double quotes is shown below:
This doesn't produce a broken string error. The quotes are quite happy to transverse several lines.
Code within double quotes is evaluated. For instance:
PHP has a function called htmlspecialchars which changes some HTML to special characters, which do not run as a program.
htmlspecialchars changes, for instance, the bracket (<) to <, which shows up as a bracket, but doesn't function as such to run code.
As a cautionary note, consider this bit of code:
Whilst variables in double-quotes will be evaluated the function, in the above is not evaluated, and the script produces "My answer is htmlspecialchars()". And the alert runs! Of course, while php knows that something is a variable (because it starts with a $), it doesn't know that htmlspecialchars is a function and treats it as a string. It does, however, evaluate the variable ($something) and causes the bad script to run. The following fixes this:
The function, htmlspecialchars, is kept outside the quotes and joined to the rest of the string using the dot (.), concatenation operator. Another use of the concatenation operator is with constants.
An alternative to using quotes is to use heredoc syntax (<<<). Begin by writing the "<<<" followed by the terminator label (which can be any valid label, I used "te"). Then write the string and finally, on a new line write the terminator. The contents of the string are evaluated. For instance