tags:

views:

51

answers:

3

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;

?

+2  A: 

global is a special language construct, it can't be used in operations as you do in example 1.

Pekka
+2  A: 

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

Slokun
This is not exactly the answer to what's asked (well, according to the (wrong) title, it is): it is clear the OP already knows about the `global` keyword, his question is rather: why can't I use the `global` keyword within operations, like I do in my first example?
Marcel Korpel
+1  A: 

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.

Tesserex
This answer makes the most sense to me. Thanks!
DKinzer