PHP global 关键字如何在使用作用域的函数内部工作?

how PHP global keyword work inside function using scope?

我写了这段代码,我明白了它的第一个功能。我边看这张w3schools的截图边练习

我只要求对第二个和第三个函数进行一些清楚的解释。

我已根据代码及其结果中看到的差异编辑了代码。

    <?php 
    $x = 5;
    $y = 10;
    function myTest1(){
        global $x, $y;
        $y = $x + $y;
        echo "test1 value using GLOBAL keyword INSIDE function is : $y <br>";
    }
    myTest1();
    echo "test1 value using GLOBAL keyword OUTSIDE function is : $y <br><br>";
    ?>

    <?php 
    $x = 5;
    $y = 10;
    function myTest2(){
        $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
        echo "test2 value using NO GLOBAL with GLOBALS[variable/index] keyword INSIDE function is nothing : $y <br>";
    }
    myTest2();
    echo "test2 value using NO GLOBAL with GLOBALS[variable/index] keyword INSIDE function is : $y <br><br>";
    ?>

    <?php 
    $x = 5;
    $y = 10;
    function myTest3(){
        global $x, $y;
        $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
        echo "test3 value using GLOBAL with GLOBALS[variable/index] keyword INSIDE function is : $y <br>";
    }
    myTest3();
    echo "test3 value using NO GLOBAL with GLOBALS[variable/index] keyword INSIDE function is : $y <br>";
    ?>

myTest1()myTest2()作用相同,因为声明global $x, $y;意味着函数内部的变量$x$y引用全局变量, 与 $GLOBALS['x']$GLOBALS['y'].

相同

但是myTest2()没有global声明。当它分配给 $GLOBALS['y'] 时,这会更新全局变量 $y,但不会更新同名的局部变量。然后它回显 $y,而不是 $GLOBALS['y']。由于尚未分配局部变量 $y,因此它不打印任何内容。

如果您启用 error_reporting(E_ALL);,您将看到来自 myTest2() 的警告:

Notice: Undefined variable: y in filename.php on line 20