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;

?

Answers


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.


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


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.


Need Your Help

JavaFX Button does not scale with windows font size settings

java fonts javafx

The buttons in my JavaFX application look very nice on all operating systems with default font settings.

PL/SQL Function to return data between dates

function plsql

im having trouble creating a function..