Curly Braces within Double Quotes in PHP
Curly braces are used to delimit variables in double quoted strings in PHP. While very useful in many situations, this can cause confusion when trying to print a combination of curly braces and variables. For example, suppose you are trying to use PHP to generate the following Javascript code:
// Desired Javascript code
var obj = {foo:1, bar:2};
The incorrect PHP code might look something like this:
// PHP code to create Javascript code (incorrect)
$data = "foo:1, bar:2";
echo "<script>var obj = {$data};</script>";
This fails because the curly braces are used to interpret the $data variable, and thus the curly braces are not outputted. The actual output of the above code would be:
// Incorrect Javascript code created by PHP var obj = foo:1, bar:2;
This is obviously incorrect and will throw a Javascript error.
Now, the funny thing is you can’t escape the curly braces in the PHP code. However, the curly braces are interpreted as a delimiter only if followed by a variable (in other words, a dollar sign). You can take advantage of this to generate the correct output in several ways:
// PHP code to create correct Javascript code
$data = "foo:1, bar:2";
echo "var obj = {{$data}};";
echo "var obj = { $data };";
echo "var obj = { $data};";
When you are actually trying to use the curly braces to define a variable, they can be placed either before or after the dollar sign, so ${foo} and {$foo} both work. The former is called simple syntax and will greedily take as many tokens as possible to form a valid variable name. The latter is called complex syntax and can be used with complex expressions, which can prove quite useful. Here are some examples:
// Value of the index 'bar' in the array $foo
echo "{$foo['bar']}";
// Value of the property 'bar' in the object $foo
echo "{$foo->bar}";
// Value of the property named $bar in the object $foo
echo "{$foo->$bar}";
// Value of the var named $name
echo "{${$name}}";
// Value of the var named by the return value of the function getName()
echo "{${getName()}}";
// Var named by the return value of $object->getName()
echo "{${$object->getName()}}";
No comments yet.
No trackbacks yet.