简体   繁体   English

PHP 将全局值分配给函数内另一个全局值的引用

[英]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.在 PHP 中使用全局变量和引用时,我遇到了一个问题。 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 ).在下面的代码中,您可以看到$a函数内部的值是5 ,但之后它又恢复了旧值 ( 1 )。 $x on the other hand has kept the value assigned inside the function.另一方面, $x保留了函数内部分配的值。

<?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?为什么$a在函数完成后丢失了它的引用?

As @Banzay noticed, I believe $a = &$x;正如@Banzay 所注意到的,我相信$a = &$x; only changes the function-scoped variable.只改变函数范围的变量。 You should use $GLOBALS to change the value in a function;您应该使用$GLOBALS来更改函数中的值;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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