Why Not Globals In PHP?

Access: any code can do anything it wants with a global value.

You’re making this point about PHP??!! I don’t think I’ve ever seen a language whose code access and such rely more on the honor system than PHP. Sucking values into a class is the only way to protect them. And even then, if you provide any write access to them at all, you’re putting the other coder(s) on the honor system. There’s simply no convenient way to link the changing of a variable’s value to the identity of just certain users.

Concurrency: Two or more instances trying to access the data can lead to the values being in an indeterminate state; race conditions on read/write

This is only really valid for data stored and manipulated at a truly global level, as in a database or SESSION. I suppose it could be done using asynchronous javascript calls (again, to truly global data sinks), but otherwise you simply won’t have async or multiple instances using the same globals. If I thought such a thing was possible, I’d figure it into the code in the first place. Normal code access in PHP is linear.

Coupling/structure/code clarity: in OO coding, you can create setters and getters which can limit access, do bounds checks or lock down values completely. Ask yourself why you’re using globals anyway? Are you avoiding passing the values from function to function? You can use sessions and such.

Same answer as before; we’re on the honor system. But by locking the value inside a class (to protect it), all you’re really doing is making it more complicated to access. Instead of $cfg = ‘green’, you’re making the programmer think more about what he’s doing, when you making it instead $cfg->set(‘green’);. Maybe that has some value. But if you’re rummaging around trying to add functionality or something to my code, you really shouldn’t be absently changing important variable values without giving it some thought. I’m certainly cognizant of this when I start drilling down into other people’s code. Trust me, I wouldn’t be making this value global unless I had a good reason.

Globals are okay in small programs.

Ummm, when is it going to dawn on PHP coders that you’re not writing War and Peace? Your code is designed to present to the user one page. That’s it. You can write a million lines of code, but it’s only ever going to show the user one page, unless you involve javascript or something. It’s one page. Not a whole accounting application.