Results 1 to 3 of 3

Thread: set a PHP variable as global once?

  1. #1
    Join Date
    Nov 2010

    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?

  2. #2
    Join Date
    Aug 2004
    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.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  3. #3
    Join Date
    Nov 2010
    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.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center