$GLOBALS['current_view']
and global $current_view
, which do you prefer and why?
views:
63answers:
4Neither, pass parameters into the methods. Every time you use globals, God kills a kitten.
If I must use globals, and I avoid them like the plague, I use global $current_view. I just prefer to always have a locally scoped variable rather than relying on super globals. But I think its a matter of preference.
Personally, I prefer the $GLOBALS['glob']
syntax because I can just copy paste the code without having to worry about declaring variables as globals. Keep in mind that you should try to keep globals to a minimum (maybe just global configuration directives, and even there...).
However, the two methods are not exactly synonymous; there's a slight difference:
function func() {
var_dump($GLOBALS['glob']);
}
function func2() {
global $glob;
var_dump($glob);
}
The first one will emit a notice if the global 'glob' does not exist. The second one won't.
In the first case, sending $GLOBALS['glob']
as an argument compiles to:
3 FETCH_R global $0 'GLOBALS'
4 FETCH_DIM_R $1 $0, 'glob'
You're fetching GLOBALS
and its index glob
in a read context; no variable is created.
The second one compiles to
compiled vars: !0 = $glob
...
2 FETCH_W global lock $0 'glob'
3 ASSIGN_REF !0, $0
You are creating a reference to the global glob
, so it is implicitly created if it doesn't exist.
Also:
function func_unset() {
unset($GLOBALS['glob']);
}
function func2_unset() {
global $glob;
unset($glob);
}
The function func()
will actually unset the global, func2_unset
will merely destroy the reference that was created.
Note that func2
is very similar to:
function func3() {
$glob =& $GLOBALS['glob'];
}
This one is however potentially less efficient. It compiles to
2 FETCH_W global $0 'GLOBALS'
3 FETCH_DIM_W $1 $0, 'glob'
4 ASSIGN_REF !0, $1
static classes ftw
class View {
private static $current = null;
public static function get_current() {
return self::$current;
}
}