3 replies [Last post]
quaoar's picture
Offline
Bug FinderEarly adopter... addicted to alphas.Getting busy with the Ubercode.Not Kulvik
Joined: 08/08/2007
Juice: 179
Was this information Helpful?

Instead of just using the superglobal array $GLOBALS?

For example I've taken to using $GLOBALS['user'] whenever I need to access a variable from the global scope. Opposed to writing for example "global $user" in a function and by that reserving that name for the rest of the functions scope.
Some functions I encounter in Drupal/UC are quite large (lots of lines of code). I personally find it easier to read code where you can easily tell if whatever variable currently being used is a global or not.

Just curious Smiling

Erlend Strømsvik
Ny Media AS
erlend@nymedia.no

Shawn Conn's picture
Offline
Administrator
Joined: 08/07/2007
Juice: 916
Nope

Other than stylistic concerns, there's no difference. Either way you're referencing same variable. I've found myself doing the same thing actually. It's one less line of code to write!

-Shawn Conn: If the Name Don't Rhyme It Ain't Mine

quaoar's picture
Offline
Bug FinderEarly adopter... addicted to alphas.Getting busy with the Ubercode.Not Kulvik
Joined: 08/08/2007
Juice: 179
Re: Nope

Actually, it may seem it's not entirely the same. (just spent some time reading about this)

Using the global keyword you are creating a reference to the value in the $GLOBALS array. Someone did some tests running functions working with the $GLOBALS array and then using references to values in $GLOBALS and the latter was slower. This was for PHP 5.0.3 (http://www.php.net/global - about halfway down the page).

I also remember some time ago, someone proposed to deprecate the global keyword from PHP. After that I stopped using it entirely.

Erlend Strømsvik
Ny Media AS
erlend@nymedia.no

Lyle's picture
Offline
AdministratoreLiTe!
Joined: 08/07/2007
Juice: 6846
Hrm... Part of it's legacy

Hrm...

Part of it's legacy syntax of C and Java where you only had the global keyword, so doing it that way feels familiar.

The rest of it's probably because $user is shorter than $GLOBALS['user']. Eye-wink So if I'm going to be using it several times in a function, I'll probably declare it global at the beginning to save just a tiny bit of extra work.

I have to agree, though. It is nice knowing for sure which variables are global from the get go.