Question on PHP and global variables shared by multiple scripts

stndn

Golden Member
Mar 10, 2001
1,886
0
0
Let's say i have script1.php with the following contents:

<?php
$GLOBALS['my_var'] = "hello world";
$GLOBALS['your_var'] = "goodbye";
?>

And I want to access those variables from inside script2.php. Which is the preferred method?

<?php
require_once ('script1.php');

# Which is a better/preferred method?

# Method 1:
global $my_var;
print $my_var

# Method 2:
print $GLOBALS['your_var'];

?>

Or is there simply no difference between the two, other than the way they are typed out?
Is there any difference if Method1 and Method2 are put inside a function instead of outside like it is now?

Thanks.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
iirc, no difference between $foo and $GLOBALS['foo']. Inside of a function you can probably read any global variable normally, but you need to "global" it if you want to write to it. Or I could be wrong.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
That's what i thought, too. Shouldn't be any difference in which one to use.
Btw, is there any danger in global-ing a global variable?

Example:
global $foo;
$foo = "hello";

# ... somewhere at the bottom
global $foo;
$foo = "hi";