Recent Posts

Showing posts with label curly braces. Show all posts
Showing posts with label curly braces. Show all posts

PHP: Curly braces strings usage

They're used to escape variable expressions. From Strings:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appear outside the string , and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>
I say "escape" because you can do this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
or

$out = "{$a} {$a}"; // same
so in this case the curly braces are unnecessary but:

$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";