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
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.