global or $GLOBALS

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Just two short questions..:

1) In a function I want to get the value of a global variable declared  
outside the function. Should I use "global $variable" or $GLOBALS[variable]?  
Are there any differences in performance or other aspects which should make  
me choose the one thing or the other?

2) Generally, is it better to pass arguments to the function instead?

Ole J  

Re: global or $GLOBALS

ojorus wrote:

Quoted text here. Click to load it


Just use:  
global $varname;
inside your function.

Don't worry about performance issues for such basic stuff unless you have a  
valid reason.

Quoted text here. Click to load it

That depends.
I think you mean if passing by reference or plain passing?

Passing by reference is faster, because normal passing involves a complete  
copy of the variable.
If you pass a variable by reference, the pointer to the object is passed.
a possible handy or harmfull sideeffect of passing by reference is that the  
function can change the content of the passed variable.

Read more here:

Happy coding. :-)

Erwin Moller

Quoted text here. Click to load it

Re: global or $GLOBALS

Also sprach Erwin Moller:

Quoted text here. Click to load it

No. See

Quote: "Note that PHP 4 is not like C: passing variables by reference is not
necessarily faster than passing them by value. Indeed, in PHP 4 it is
usually better to pass a variable by value, except if the function changes
the passed value or if a reference ... is being passed."

PHP simply creates another entry in the symbol table pointing to the same
stored value and does not copy it until one of the variables is actually
changed. Thus, references would not necessarily be faster.


Re: global or $GLOBALS

ojorus wrote:
Quoted text here. Click to load it

Access through $GLOBALS is slightly slower, since it requires two
look-ups: one for the $GLOBALS array, another for the actual element
within the array. Using the global keyword is the preferred method.

Quoted text here. Click to load it

Yes, it's in general better to pass arguments. It makes your code more
flexible obviously as you can pass in different arguments. Using global
variables also makes your functions non-reentrant, which is serious
headache in any complex application.

Site Timeline