Sometimes you need to make clear to PHP what is actually the variable name. I have discovered that a colleague and I had been doing it slightly differently.
Say you had a variable $foo
and wanted to output that with _constant_string appended
I had been using
return "<input type='hidden' name='${foo}_constant_string' value='true' />";
whereas my colleague is using
return "<input type='hidden' name='{$foo}_constant_string' value='true' />";
(slightly contrived example to simplify it).
My quick tests don't reveal an obvious difference, but I am curious: Is there a difference? Is there a reason to prefer one over the other?
Edit: My example above used strings but my question was more general - I should have explicitly said so. I knew you could use curly braces for escaping, but hadn't found the specific point of if there was (in any situations) differences between the two ways of using them. I got the answer: there isn't for strings (which is what the "duplicate" post is about) but is for arrays and objects (thanks @dragoste).
It seems, there is no difference in any PHP version
$foo = 'test';
var_dump("$foo");
var_dump("{$foo}");
var_dump("${foo}");
Test: https://3v4l.org/vMO2D
Anyway I do prefer "{$foo}"
since I think it's more readable and works in many other cases where other syntax doesn't.
As an example let's try with object property accessing:
var_dump("$foo->bar"); //syntax error
var_dump("{$foo->bar}"); // works great
var_dump("${foo->bar}"); //syntax error
The same case are arrays.
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex
No, there is no differentce.
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
Php manual
Answer on stackoverflow
Another way use it for variable:
$foo = 'test';
$test = 'foo';
var_dump("{${$foo}}"); //string(3) "foo"
Or for array:
$foo = ['foo','test'];
var_dump("{$foo[0]}"); //string(3) "foo"
var_dump("${foo[1]}"); //string(4) "test"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With