core class and global variables...
Results 1 to 2 of 2

Thread: core class and global variables...

  1. #1
    Senior Member
    Join Date
    Sep 2011

    core class and global variables...

    Well I've heard it many many times how global variables are bad and one should avoid it as much as possible. While I was browsing into Vbulletin and MyBB's core class(class Vbulletin/class MyBB), however, I found they were instantiating an object of the same name and passing it to function files as global $Vbulletin/global $MyBB frequently. The global object contains properties like cookies, session, currentuser and so on. If an object is declared as global, it is essentially a huge collection of global variables! Why would Vbulletin and MyBB do this? Or is the security issue for Global variables over-exaggerated by advanced programmers? I'm so confused now...

    Also I've heard that dependency injection is a possible way to avoid using globals, but I have no idea how to use it. Anyone familiar with dependency injection here, and know how to replace globals by dependency injection? Just curious
    Last edited by Lord Yggdrasill; 04-14-2012 at 08:16 AM.

  2. #2
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    As I understand it, DI just means that you inject and objects upon with the subject class depends via a method (which can include the constructor).
    PHP Code:
    class Foo
      public function 
    __construct(Dependency1 $dependency1)
    $this->dependency1 $dependency1;
    setDependency2(Dependency2 $dependency2)
    $this->depenedency2 $dependency2;

    $d1 = new Dependency1();
    $foo = new Foo($d1);
    $foo->setDependency2(new Dependency2()); 
    Note that you can use either instantiation technique as appropriate to your needs/preferences, e.g. the following would work just as well:
    PHP Code:
    $foo = new Foo(new Dependency1());
    $d2 = new Dependency2();
    There are arguments for and against injecting the dependencies via the constructor or a setter method. I generally start with the constructor and move it to a setter if it seems better that way.
    "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

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