The Building Blocks / Page 2
[previous] [next]
The Building Blocks:
Data Types, Literals, Variables, and Constants
String Literals and Quoting
We introduce strings in this chapter but Chapter 6, "Strings," provides a more comprehensive coverage. String literals are a row of characters enclosed in either double or single quotes.[1] The quotes must be matched. If the string starts with a single quote, it must end with a matching single quote; likewise if it starts with a double quote, it must end with a double quote. If a string of characters is enclosed in single quotes, the characters are treated literally (each of the characters represents itself). We can say the single quotes are the democratic quotes: All characters are treated equally.
Double quotes do not treat all characters equally. If a string is enclosed in double quotes, most of the characters represent themselves, but dollar signs and backslashes have a special meaning as shown in the following examples.
Single quotes can hide double quotes, and double quotes can hide single quotes:[2]
1. PHP always null-terminates strings internally and keeps track of the length of the string.
2. PHP recognizes editors that use straight quotes, such as vi or Notepad, but not editors that automatically transform straight quotes into curly quotes.
An empty set of quotes is called the null string. If a number is enclosed in quotes, it is considered a string; for example, "5
" is a string, whereas 5
is a number.
Strings are called constants or literals. The string value "hello
" is called a string constant or literal. To change a string requires replacing it with another string.
Strings can contain escape sequences (a single character preceded with a backslash). Escape sequences cause a character to behave in a certain way; for example, a "\t
" represents a tab and "\n
" represents a newline. The backslash is also used for quoting a single character so that it will not be interpreted; for example, \$5.00
where the dollar sign in PHP is used to represent variables rather than money. \$5.00
could also be written as '$5
' because single quotes protect all characters from interpretation.
Here documents, also called here-docs, provide a way to create a block of text that simplifies writing strings containing lots of single quotes, double quotes, and variables (see Example 4.4).
Example 4.3
Explanation
|
[previous] [next]
URL: