【发布时间】:2012-12-24 10:11:05
【问题描述】:
我正在编写一个使用 PHP 的游戏脚本,并以与我构建许多网站的方式类似的方式来处理它。我有一个习惯,即声明一个变量,它是一个 stdClass,它包含许多其他对执行很重要的变量。然后,如果我需要函数内部的某些东西(如果它没有传入参数),我只需使用全局 $variable,在本例中为 $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);
因此,如果我要在函数中使用上述变量之一,我会这样处理它。
public function run() {
global $ar;
//do something with the variable..
}
有人会建议不要这样做吗?使用单个变量并将其包含在许多函数中是一种避免的坏习惯吗?我知道创建只使用给定参数的函数是可取的,但我问的是关于 PHP 性能而不是编程清晰度的问题。谢谢!
【问题讨论】:
-
这是Registry Pattern。总有更好的方法
标签: php performance global-variables scope global