05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

echo "$who was $where";<br />

Kilroy was here<br />

The complex way is to surround the variable being interpolated with curly braces.<br />

This method can be used either to disambiguate or to interpolate array lookups. The<br />

classic use of curly braces is to separate the variable name from surrounding text:<br />

$n = 12;<br />

echo "You are the {$n}th person";<br />

You are the 12th person<br />

Without the curly braces, <strong>PHP</strong> would try to print the value of the $nth variable.<br />

Unlike in some shell environments, in <strong>PHP</strong> strings are not repeatedly processed for<br />

interpolation. Instead, any interpolations in a double-quoted string are processed,<br />

then the result is used as the value of the string:<br />

$bar = 'this is not printed';<br />

$foo = '$bar'; // single quotes<br />

print("$foo");<br />

$bar<br />

Single-Quoted Strings<br />

Single-quoted strings do not interpolate variables. Thus, the variable name in the following<br />

string is not expanded because the string literal in which it occurs is singlequoted:<br />

$name = 'Fred';<br />

$str = 'Hello, $name'; // single-quoted<br />

echo $str;<br />

Hello, $name<br />

The only escape sequences that work in single-quoted strings are \', which puts a single<br />

quote in a single-quoted string, and \\, which puts a backslash in a single-quoted<br />

string. Any other occurrence of a backslash is interpreted simply as a backslash:<br />

$name = 'Tim O\'Reilly'; // escaped single quote<br />

echo $name;<br />

$path = 'C:\\WINDOWS'; // escaped backslash<br />

echo $path;<br />

$nope = '\n'; // not an escape<br />

echo $nope;<br />

Tim O'Reilly<br />

C:\WINDOWS<br />

\n<br />

Double-Quoted Strings<br />

Double-quoted strings interpolate variables and expand the many <strong>PHP</strong> escape<br />

sequences. Table 4-1 lists the escape sequences recognized by <strong>PHP</strong> in double-quoted<br />

strings.<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Quoting String Constants | 73

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!