3 ms·
Globals can make sense. In C it isn't unusual at all to see a variable that is global in file scope only, which is similar in effect to how class variables are
by arghnoname 16y ago
Globals can make sense. In C it isn't unusual at all to see a variable that is global in file scope only, which is similar in effect to how class variables are treated within the class definition in a variety of OOP languages.
The problem is PHP's scoping rules don't lend themselves well to this kind of thing. If you were to use a PHP library, for instance, that used the same practices you are using, say a parser, you might find that depending on the include order $look_ahead now means something different.
This kind of "all I did is include a file and everything broke" error is really annoying to find. Constants are useful for this, because at least it will flag an error/warning. Now that PHP has (is getting? It's been a while) namespaces, you can limit its scope and make it less likely to collide.
For the case of databases, it is fairly common to use PHP's builtin functionality to reuse the database connection without having to rely on a global handle. Again, if someone shares your practices the variable could end up getting stepped on. Throw in autoloading and maybe it only occurs when some confluence of events leads to some specific file being included that usually isn't.
So there's a reason for concerns about globals. Putting everything in a singleton with static variables is not really different, but in my mind mostly just namespaces it so your globals don't get in trouble with someone else's globals. I've found in practice that I've only rarely needed global variables or singleton classes housing global variables. This probably largely depends on your style of coding.
I haven't written in PHP for years now so if I've gotten any details wrong please forgive me. Hopefully though you can see some ways that frequent use of globals can lead to hard to find bugs. A lot of programming techniques (OOP, closures, for example) are designed to help pass around state in ways that don't lead to these kinds of problems.