Here follows the examples you posted,
When you use {}
you make sure the entire path of the object gets evaluated. If you remove them it will only evaluate $obj->values
which returns Array
.
$obj->values[3] = "Name";
echo "This works too: {$obj->values[3]}"."\n"; // CORRECT: This works too: Name
echo "This works too: $obj->values[3]"."\n\n"; // ERROR: This works too: Array[3]
In the first two examples $name
is evaluated first, and you will be left with {$mike}. Since you have the curly braces outside the new variable name, this too will be evaluated, and will translate to the string Michael
instead. In the last example you will be left with $mike
.
$name = "mike";
$mike = "Michael";
echo "This is the value of the var named $name: {${$name}}"."\n"; // This is the value of the var named mike: Michael
echo "This is the value of the var named $name: {$$name}"."\n"; // This is the value of the var named mike: Michael
echo "This is the value of the var named $name: $$name"."\n\n"; // This is the value of the var named mike: $mike
This example is similar to the one above, but instead of using the variable $name, a function is used instead. If you do not have the curly braces {}
around the function (example #2), but around $getName()
, PHP will try to to access the function $getName
, which is not a legal function name.
The last example $getName() will fetch the value of the variable $getName and the () will be left alone. So if you would have $getName = "Heya";
, it would become Heya()
.
function getName() { return "mike"; }
echo "This is the value of the var named by the return value of getName(): {${getName()}}"; // This is the value of the var named by the return value of getName(): Michael
echo "This is the value of the var named by the return value of getName(): {$getName()}"; // Fatal error: Function name must be a string
echo "This is the value of the var named by the return value of getName(): $getName()"; // This is the value of the var named by the return value of getName(): ()