2

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?

Community
  • 1
  • 1
Robert
  • 6,660
  • 5
  • 39
  • 62

3 Answers3

14

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 2
    +1, I agree with you Pekka, and just because PHP is forgiving enough to convert the bare string into a literal for you, doesn't mean you should get into a habit of using it. – Anthony Forloney Mar 09 '10 at 01:17
  • @Anthony true, plus (I edited my answer a bit) it massively sabotages the use of constants - you can never really rely on their being set, and have to check them using `defined`. The proper way would be to throw a fatal error if a constant has not been defined. – Pekka Mar 09 '10 at 01:19
  • Well, you just have to report warning-level errors and vigilantly fix them. But it's still a PITA. – Xiong Chiamiov Sep 04 '13 at 20:23
1

This doesn't probably count as legitimate, but my friend's tweetable proof-of-concept MVC framework, TweetMVC eschews quotes in a few spots to squeeze a few more characters in, e.g.:

foreach(c('mod')as$f)require"t/$f.php";@list($c,$m,$a)=explode('/',@$_GET[r],3);$c=$c?:c('dc');$o=(@include"c/$c.php")?@new$c($m,$a):e(1)
davidtbernal
  • 13,434
  • 9
  • 44
  • 60
0

The only time you would use a bare string as a key is if it's been previously used in define() for a constant.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358