design to not to use "global"

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
julian_lp
Forum Contributor
Posts: 121
Joined: Sun Jul 09, 2006 1:00 am
Location: la plata - argentina

design to not to use "global"

Post 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
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: design to not to use "global"

Post 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.
User avatar
allspiritseve
DevNet Resident
Posts: 1174
Joined: Thu Mar 06, 2008 8:23 am
Location: Ann Arbor, MI (USA)

Re: design to not to use "global"

Post by allspiritseve »

This looks like a simple version of the Registry pattern... search around on here, sitepoint, google, you'll find plenty of examples.
User avatar
julian_lp
Forum Contributor
Posts: 121
Joined: Sun Jul 09, 2006 1:00 am
Location: la plata - argentina

Re: design to not to use "global"

Post 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
Post Reply