Convention for accessing global variables
Obviously, there are two ways to access global variables. 1. Via the global keyword: <?php global $user; print $user->uid; ?> 2. By accessing the $GLOBALS array directly: <?php print $GLOBALS['user']->uid; ?> Is there an established convention for this within Drupal core? The majority of cases in HEAD use the global keyword (~470) instead of accessing the $GLOBALS array (~40 cases). Is this something that should be made a coding style issue for consistency across the codebase? As a sidenote, accessing the $GLOBALS array directly in on average 25% faster than using the global keyword. Of course, both run fast enough that the difference is hardly noticeable. Brian Vuyk
Brian Vuyk wrote:
two ways to access global variables As far as I am concerned it comes down to how often the global variable is to be accessed. Execution speed is not the only speed to worry about here. Code loading speed is also important, and disk access is pretty slow (by computer standards). So, if the global is to be accessed only once, it is probably going to be more compact to use the $_GLOBAL form. If it is going to be accessed many times (as $user often is), then I would use the "global" form.
And, to me, that should be the standard. Too often we focus more on the look of the code and not enough on its speeds (both execution and loading). With the efforts that were begun in D6 and further refined in D7, it would appear that the core developers are also concerned with loading speed. Nancy E. Wichmann, PMP Injustice anywhere is a threat to justice everywhere. -- Dr. Martin L. King, Jr.
On 09/12/2009 3:45 PM, Brian Vuyk wrote:
Is there an established convention for this within Drupal core? I'm sure I'm not the only person who's done something like the following by mistake:
<?php global $user; // Do one thing like access $user->uid. // Other, unrelated code. $user = user_load(...); // Boom! This makes me think that standardizing on $GLOBALS would be a good thing. Can you link to where you found the 25% faster benchmark? --Andrew
Andrew Berry wrote:
I'm sure I'm not the only person who's done something like the following by mistake $user = user_load(...);
No, I'd guess at least half the developers on this list have done that. That's why the guideline in core is to use $account for a user object. It took me a few mistakes like that to realize the wisdom in it. Nancy E. Wichmann, PMP Injustice anywhere is a threat to justice everywhere. -- Dr. Martin L. King, Jr.
participants (3)
-
Andrew Berry -
Brian Vuyk -
Nancy Wichmann