Adam Adam - 6 months ago 15
PHP Question

PHP: Is there a difference between {$foo} and ${foo}

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).

Answer

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