- Strings may be quoted with either single ' (apostrophy) or double " (quotation) marks. If you quote your string with one of these characters, the other may be used in the string.
- Strings may span several lines. PHP will keep reading until you end the quotation. So, you can see that forgetting a closing quotation mark will cause all sorts of problems. PHP has no problem with the following:
$sql = " SELECT FirstName, LastName, Address, City FROM Reporter WHERE LastName LIKE '$initial%' " ;
- Strings quoted with single quotes will be interpreted literally. That is, no variable interpolation will take place:
- The string 'Bill owes $5.00 by Friday' will correctly interpret the dollar sign as part of the string.
- The string 'Bill owes $owed by $day' will incorrectly interpret the dollar signs that are part of the variable names as literal dollar signs. That is, they will not be treated as variables.
- With two exception, the backslash character will be interpreted as a literal backslash. The first exception is if the backslash precedes a single quote. In that case, it "excapes" the single quote. This also means a string ending with a backslash needs two backslashes so the first backslash can escape the second instead of the single quote. That's the second exception. A single backslash and a double backslash are both treated as a single literal backslash.
- Strings quoted with double quotes will be interpolated:
- The string "Bill owes $5.00 by Friday" will cause an error (since $5 is not a valid variable name).
- The string "Bill owes $owed by $day" will substitute the values of the variables $owed and $day into the string.
- The backslash character followed by another character will be interpolated in a special manner.
- A backslash followed by a dollar sign will be interpolated as a literal dollar sign (not the first character in a variable name). So, "Bill owes \$5.00 by Friday" is equivalent to 'Bill owes $5.00 by Friday'.
- A backslash followed by a double quote will be a literal double quote (so you can imbed double quote characters in strings).
- A backslash followed by one of a number of letters will be the associated control character (i.e. \t is a tab, \n is a new line, etc.)
- Finally, you may use "heredocs" to quote longer multiple line strings. Variable interpolation is the same as for double quotation marks except you don't need to excape double quotes. A heredoc is done like this:
$sql = <<< end_of_quote SELECT FirstName, LastName, Address, City FROM Reporter WHERE LastName LIKE '$initial%' end_of_quote;
Note that the variable $initial is interpolated. The string may contain single and double quotes. The only thing the string may not have is the string end_of_quote; as the first thing on a line.
Copyright © 2003
Henry H. Hartley
All Rights Reserved