Page 1 of 1

design to not to use "global"

Posted: Tue Jun 17, 2008 4:26 pm
by julian_lp
hello folks,

reading some piece of old program (which I need to modify right now), I encountered a lot of global vars & objects calls
so I was wondering how and what do you do in order to not needing to call the hated(for me at least) "global" keyword

I'd like to expose as well the path that I'm thinking I'm gonna take:

(pseudo code and simplified)

Code: Select all

 
$obj1 = new Obj1;
$obj2 = new Obj2;
$obj3 = new Obj3;
...
 
$obj_array = array('obj1'=>$obj1, 'obj2'=>$obj2, 'obj3'=>$obj3, ......)
 
$obj1->globals($obj_array)
$obj2->globals($obj_array)
$obj3->globals($obj_array)
....
 
After then, I could just work inside each class (or even indide a particular object instance) just accesing the array field "gloabals"

Code: Select all

 
 
$obj2_reference =  $obj1->GetGlobal('obj2');
 
or inside the class 
 
private function ListObjects(){
    if (isset($this->FGlobalsArray)){
        for .....
    }
}
 
I'd like to read your own aproachs to this guys...

regards

Re: design to not to use "global"

Posted: Tue Jun 17, 2008 5:08 pm
by Eran
You should explore the singleton / registry patterns. It's best however if you store information that you need globally as static members of a class which would put them in a relevant context.

Re: design to not to use "global"

Posted: Tue Jun 17, 2008 5:09 pm
by allspiritseve
This looks like a simple version of the Registry pattern... search around on here, sitepoint, google, you'll find plenty of examples.

Re: design to not to use "global"

Posted: Tue Jun 17, 2008 5:58 pm
by julian_lp
thanks, you're absolutely right, what I was looking for was the Registry patter

this page helped me a lot to understand how it works
http://www.patternsforphp.com/wiki/Registry

regards-julian