php的$GLOBALS例子

 1 <?php 
 2    $test = "test";
 3    function show1($abc){//直接把参数传入函数,函数能用
 4        echo $abc.'<br>';
 5    }
 6    
 7    function show2(){//不给函数传参数,所以使用不了外部变量,报错
 8        echo $test.'<br>';
 9    }
10    
11    function show3(){//可以通过$GLOBALS来调用外部变量
12        echo $GLOBALS['test'].'<br>';
13    }
14    echo "it is show1 function<br>";
15    show1($test);
16    echo "it is show2 function<br>";
17    show2();
18    echo "it is show3 function<br>";
19    show3();
20    
21 ?>
View Code

运行结果如下:

PS:补充一下$GLOBALS的知识:

       $GLOBALS :引用全局作用域中可用的全部变量

                      一个包含了全部变量的全局组合数组。变量的名字就是数组的键。

  范例:

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "
";
    echo '$foo in current scope: ' . $foo . "
";
}

$foo = "Example content";
test();
?>
View Code

以上例程的输出类似于:

$foo in global scope: Example content
$foo in current scope: local variable
View Code
 
原文地址:https://www.cnblogs.com/tommy-huang/p/4184587.html