set a PHP variable as global once?
I want to make an instance of my class as global variable. Is this possible without having to always declare it was a global variable inside each individual function that use that variable?
In other words, lets say I use that instance in 100 functions. Is there a way to specify that variable is global once instead of 100 times?
There may be several ways to approach this, but the "best" answer will probably depend on a better understanding of why you need/want to do this. Perhaps the class in question could be made into a Singleton Pattern class, and then instantiated wherever needed, but this can have many of the same drawbacks as using global variables. You could assign on instance of it to the $GLOBALS array, at which point it is accessible anywhere in the script, but this is probably even more injurious to the goal of loose coupling than a singleton class would be. The loosest coupling would be to simply pass the object as part of each relevant function and/or constructor argument list, avoiding all the bad things about using globals, though potentially cluttering up the code with functions/objects passing around objects that they themselves do not use. Or, if you expect to have several such "global" things you need to pass around, maybe create one Registry Pattern object that can contain these system-wide objects, and just pass that one object around as needed, though that can still tighten coupling since you now depend on that registry object being populated with whatever things its various using classes/functions will need.
So, you need to choose based on your particular circumstances, but my general advice is to err on the side of loose coupling as opposed to saving a few keystrokes now.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
How to Ask Questions the Smart Way
(not affiliated with this site, but well worth reading)
I ended up taking a function approach instead...
I wrote all the details in this reply but edited out (was too long)... Long story short: I was turned a simple problem into something more complicating, especially considering it almost wasn't a problem to begin with... I didn't even need a class.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)