views:

165

answers:

5

We use instantiate and put system critical objects in $GLOBALS for easy access from anywhere (e.g. DB, Cache, User, etc.).

We use $GLOBALS so much that it would (yes, really) drop the amount of code quite a bit if I could reference it like $G = &$GLOBALS for a shorthand call.

The problem is that, per my experience and several hours of Googling, I have not found any construct in PHP which allows you to 'flag' a var as global, making $GLOBALS first class, and everything else second class.

Am I missing something? Is this possible?

A: 
global $variable; //?
Petr Peller
This only opens a hole in an established scope, it is not proactive in breaking through child scopes.
Spot
+2  A: 

Instead of putting everything into $GLOBALS you might want to take a look into the registry concept that is widespread in the php world.

However, having many global variables/objects is a sign of bad design and high coupling. Using something like $G guarantees spaghetti code and a soon-to-come maintenance nightmare. Who cares if you can drop the amount of code by a few characters?

middus
Spot
Why not load the registry prior to any other operation ?
Benoit
+1  A: 

In addition to the registry concept Middus points out, there are several approaches and concepts around this, some of which you can find in the answers to this question:

In a PHP project, how do you organize and access your helper objects?

Pekka
That is a great link! Thank you very much!
Spot
A: 

No, but you can use a little trick. Create a global function by the same name as your global var, and have it return the global instance. Eg.:

function db() {
  return $GLOBALS['db'];
}

You can now write your code as:

...
$stuffs = db()->query("select * from stuff");
...

You may recognise this as a variant over the singleton pattern, but a syntactically much more pleasant one.

Others have mentioned it, but you should also consider not using global objects in the first place. I generally prefer to pass objects in to there where it's needed (dependency injection). I'm not overly found of the registry pattern though.

troelskn
A: 
<?php

function &G($name) {
    if(func_num_args() > 1) {
        $GLOBALS[$name] = func_get_arg(1);
    }
    return $GLOBALS[$name];
}


G('test', 'hey');

echo G('test'); // outputs hey
echo $test; // outputs hey

$b =& G('test');
$b = 'hello';

echo G('test'); // outputs hello
echo $test; // outputs hello
Kamil Szot