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 09:16 AM.
High Energy Magic Dept.
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).
Note that you can use either instantiation technique as appropriate to your needs/preferences, e.g. the following would work just as well:
public function __construct(Dependency1 $dependency1)
$this->dependency1 = $dependency1;
public setDependency2(Dependency2 $dependency2)
$this->depenedency2 = $dependency2;
$d1 = new Dependency1();
$foo = new Foo($d1);
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.
$foo = new Foo(new Dependency1());
$d2 = new Dependency2();
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." ~ from Nation, by Terry Pratchett
"But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)