ApplePearPerson :
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?
0stone0 :
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;
}
1
5
5
5
5
5
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=376631&siteId=1