2

While playing around with globals and references in PHP I came across a problem. I wanted to set a variable to the reference of another variable inside a function. To my surprise, the global variable lost its reference after the function call.

In the code below you can see that inside the function $a gets the value 5, but afterwards it has its old value back (1). $x on the other hand has kept the value assigned inside the function.

<?php

$a = 1;
$x = 2;
function test() {
    global $a;
    global $x;

    $a = &$x;
    $x = 5;

    echo PHP_EOL;
    echo $a . PHP_EOL;
    echo $x . PHP_EOL;
}

test();

echo PHP_EOL;
echo $a . PHP_EOL; // $a is 1 here instead of 5
echo $x . PHP_EOL;

$a = &$x;

echo PHP_EOL;
echo $a . PHP_EOL;
echo $x . PHP_EOL;

Outputs:

5
5

1
5

5
5

Why does $a lose its reference after the function is done?

3
  • I'm not proficient in globals, as these are evil. I think you need to define global on first declaration of $a, ie before function definition. Commented Mar 31, 2020 at 14:45
  • That doesn't seem to change anything unfortunately Commented Mar 31, 2020 at 14:49
  • 2
    As I know global vars can be changed via $GLOBAL array, I mean instead of $a you need to use $GLOBALS[$a] if you want to change it Commented Mar 31, 2020 at 14:51

1 Answer 1

1

As @Banzay noticed, I believe $a = &$x; only changes the function-scoped variable. You should use $GLOBALS to change the value in a function;

function test() {
    global $a;
    global $x;

    $GLOBALS['a'] = &$x;
    $x = 5;

    echo PHP_EOL;
    echo $a . PHP_EOL;
    echo $x . PHP_EOL;
}

Try online!

1
5

5
5

5
5
Sign up to request clarification or add additional context in comments.

1 Comment

That seems to work, although I still find it weird that $x can be changed with a static variable but $a can't with a reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.