3 ms·
You're specifically using it for configuration/preferences though. You should consider changing it to a constant instead as that's what they really are. The pr
by _Lemon_ 16y ago
You're specifically using it for configuration/preferences though. You should consider changing it to a constant instead as that's what they really are.
The problem is passing state around in global variables. Any code can (and readily does) modify the state which is the problem.
- chime 16y ago$db wouldn't work as a constant. You're right that look_ahead/company_address would work as a define("CONSTANT") better but honestly, I hate not putting a $ sign in front of a value (constant or variable). I am more prone to missing a $ than redefining a global. I don't remember ever having the problem of redefining a global unintentionally. I can give 20 examples of when I missed a $ symbol and PHP gave me an error/notice. If PHP constants had a symbol akin to $ (say #), I would definitely use them. But I just feel dirty typing "echo LOOK_AHEAD;" in one place and "echo $look_ahead_partial;" in another because I don't want to get in the habit of putting $ in some places and not putting them in others.
- _Lemon_ 16y ago$db is something different altogether, in my code I have a cheap Database class and each model creates a new one -- but it relies on the MySQL functions it uses to re-use the database connection. So in reality it's the same thing. The problem with not using a constant where it's necessary is that you're communicating the wrong thing to someone else or even yourself 6 months down the line. You might want to re-evaluate what you see as "ugly code" especially if it changes how you write the code.
- robryan 16y agoNot only that but depending what kind of db wrapper class you have you probably want it to be modified by the code that touches it. Sure you could pass it around, I guess it depends on how many people touch the code. Personally I global the database wrapper, the user session class and config stuff (which yes I could use constants). Although if the code base I'm referring to wasn't 95% me coding I would probably consider using global less.
- nir 16y agoOn the other hand, when someone reads "echo LOOK_AHEAD" they immediately know it's a constant and thus (a) global and (b)(more importantly) defined once and never modified by the code. With "echo $look_ahead" there's no indication of that, and in the future another dev might add something that modifies $look_ahead's value and break other parts of the code, making for sneaky bug (which incidentally is why non-constant globals are so disliked ;))