简体   繁体   中英

PHP assign global value the reference of another global value inside a function

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM