phpstringarrayskeybare

Is there any legitimate use for bare strings in PHP?


This question got me thinking about bare strings.

When PHP sees a string that's not enclosed in quotes, it first checks to see if it's a constant. If not, it just assumes it's a string and goes on anyway. So for example if I have

echo $foo[bar];

If there's a constant called bar it uses that for the array key, but if not then it treats bar as a bare string, so it behaves just like

echo $foo["bar"];

This can cause all kinds of problems if at some future date a constant is added with the same name.

My question is, is there any situation in which it actually makes sense to use a bare string?


Solution

  • Nope, I can not see a single instance where it would make sense, and it always is dangerous. Using strings without quotes should absolutely be reserved to address constants. I don't understand how the inventors of PHP could decide to introduce this ridiculous behaviour at all - it makes the proper use of constants almost impossible (because if you try to access a constant that has not been defined, PHP will silently and stupidly generate a string) without giving any benefit.