Correct in your replies:global $var;tells the function to collapse the local and global values into the global variable.
There is no way to create a "superglobal" as in $_GET that will then be ALWAYS global. But usingglobalor$GLOBALS[]will allow you to access them as needed.
Unless you're doing a lot with the value, my favorite method is this:
PHP Code:function myfunc() {
$myvar = $GLOBALS['myvar'];
echo $myvar; //or something else...
}
Globals can get complicated, but the simple rule I use is this: if you need to use a global value, declareglobal $var;as the first line inside your function (or possibly within a conditional if needed). Alternatively use $GLOBALS and there will be no confusion (hopefully), and at the very least no ambiguity.
What I don't know about the 'global' keyword is what happens when you do this at a weird time:
I haven't tested this (never really needed to), but this is a possible place of much confusion so just make sure you set everything global you need at the start or use $GLOBALS, and you'll be fine.PHP Code:$myvar = 1;
function myfunc() {
$myvar = 2;
global $myvar;
echo $myvar; //2? 1?
}
myfunc();
echo $myvar; //2? 1?
I'm planning to rewrite everything on my current project, when I get to it, to use $GLOBALS instead of 'global'.
Now, if you want to play with something more confusing, the&operator in PHP is very complex. This is used in function calls.
And it can do other things. Declaring "&" at runtime generates a deprecated warning, though. (Ex: callingPHP Code:$var = 1;
function func(&$v) {
$v = 2;
}
func($var);
echo $var; //2!!
myfunc(&$var);, rather than having that as a default in the function definition).
traq, regarding constants:
I hate constants. I wish they were redefinable. I guess this would change their nature entirely, but they're very near useless except to store never-variable information. And at that, it's much more likely that you'll not even care what's in them, but that they are set at all.
The only exception I make to this is that they're great for a security system: on your primary page (index?) establish:
define('MYSITE',1);
Then in any other pages, to make sure this is being accessed properly:
if (!is_defined('MYSITE')) { exit; }
And that's it. This allows you to ignore scope and just deal with this simple value. You could also do more things like set that the user has passed the login, etc., but that gets too variable (no pun intended), and constants are no longer very helpful.

