[Previous] [Contents] [Next]


Variable substitution

Variable substitution provides a convenient way to output variables embedded in string literals. When PHP parses double-quoted strings, variable names are identified when a $ character is found and the value of the variable is substituted. We have already used examples earlier in this chapter such as:

$cm = 127;
$inch = $cm / 2.54;

// prints "127 centimeters = 50 inches"
echo "$cm centimeters = $inch inches";

When the name of the variable is ambiguous, braces {} can delimit the name as shown in the following example:

$memory = 256;

// Fails: no variable called $memoryMbytes
$message = "My computer has $memoryMbytes of RAM";

// Works: Curly braces are used delimit variable name
$message = "My computer has {$memory}Mbytes of RAM";

// This also works
$message = "My computer has ${memory}Mbytes of RAM";

Braces are also used for more complex variables, such as multidimensional arrays and objects:

echo "Mars is {$planets['Mars']['dia']} times the diameter of the Earth";

echo "There are {$order->count} green bottles ...";

Example 2-4 shows how the multidimensional array $planets is assigned, and objects and the member access operator -> are discussed in Section 2.11.


[Previous] [Contents] [Next]