Adam Adam - 2 years ago 76
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

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?

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 Source

It seems, there is no difference in any PHP version

    $foo = 'test';      


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download