4

Possible Duplicate:
Registry design pattern…good or bad?

I am working on a game script that uses PHP and am approaching it in a similar way to how I build many of my websites. I have a habbit of declaring a single variable that is a stdClass holding many other variables that are important to execution. Then if I ever need something inside a function (if its not passed in the parameters), I simply use global $variable, in this case $ar.

$ar = new stdClass;
$ar->i = new stdClass;
$ar->s = new stdClass;

$ar->i->root = "/home/user";

/* Directory where log files are to be stored. */
$ar->i->logs = "{$ar->i->root}/logs";

/* Directory where the banlist is. */
$ar->i->bl = "{$ar->i->root}/customize/settings/bannedaccounts.txt";

/* Directory where the silencelist is. */
$ar->i->sl = "{$ar->i->root}/customize/settings/silencedaccounts.txt";

/* How many points should be awarded for 1st place, 2nd place... etc. */
$ar->s->points = array(10, 7, 5, 4, 3, 2, 1, 1, 1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1);

So if I were to use one of the above variables in a function, I would approach it like this.

public function run() {
  global $ar;
  //do something with the variable..
}

Would anyone advise not to do this? Is using a single variable and including it in a lot of functions a bad practice to avoid? I know that it is advisable to create functions that work with just the parameters given, but I am asking this in regard to PHP performance and not programming clarity. Thanks!

Community
  • 1
  • 1
Tristan
  • 2,349
  • 16
  • 11
  • 3
    This is the [Registry Pattern](http://martinfowler.com/eaaCatalog/registry.html). There's always a better way – Phil Jan 10 '13 at 04:36

1 Answers1

1

Elements of data that come together to represent an object should be an object. If you have stuff that is unrelated, don't stuff it in the same object.

If you need a global scope (and you usually don't), you can use $GLOBALS. However, I suggest you follow OOP principals, for most projects. At a minimum, use function parameters.

If you had a library of functions like run() that need those variables (or, even just run()!), have a utility class where those variables are members of that class.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Well, what I normally do is store my engines (almost like libraries) inside of the global var, so I use for example `$ar->e->db = new Database();` But then everything inside of there will become a variable at `$ar->e->db->variable`. I like working like that, but I'm not sure if its a bad practice. – Tristan Jan 10 '13 at 04:40
  • 1
    There is no need to do that. If you want a truly global DB connection (which can make sense in certain cases), then use `$GLOBALS`. – Brad Jan 10 '13 at 04:47