Why is it that I can't reference a global variable directly in PHP?
I'm curious to know why 开发者_如何学运维the following code behaves differently?
The following does not work:
$_variable &= global $_global;
echo $_variable;
The following works:
global $global;
$_variable &= $_global;
echo $_variable;
?
global
is a special language construct, it can't be used in operations as you do in example 1.
The global
keyword is used to say, "Use the global variable by this name, rather than a local one." The most common use is like this:
$name = 'Slokun';
printName();
function printName() {
global $name; // Use the global, rather than function-local, version
echo $name;
}
which would print
Slokun
Compare to:
$name = 'Slokun';
printName();
function printName() {
echo $name;
}
which wouldn't print anything
Think of the global
keyword more like a verb than an adjective. Your first example says "reference assign the global known as $_global to $_variable". But global
is not an adjective. The second example, which is correct, says to php, "Treat $_global as a global", or "global-ify $_global", and then make the assignment.
Your code should be wrong. Passing a value by reference should be:
1.)
$_variable =& $_global;
2.)
$_variable = & $_global;
3.)
$_variable = &$_global;
1~3 are the same thing.
精彩评论