php中的global及GLOBALS的一些問題
首先看一個簡單例子
$a = 'scnjl';function test() {global $a;unset($a);}test();var_dump($a);function test1() {unset($GLOBALS['a']);}test1();var_dump($a);
?這裡輸出的結果是:
string(5) "scnjl" NULL
可以看到其實global在函數中使用的時候,並沒有直接用到變數$a,而是複製了一個指向$a的值的變數,所以當unset以後,全域變數$a並沒有被unset,而$GLOBALS['a']直接代表了全域變數$a。
這是global 和 GLOBALS的區別吧。
?
今天在弄一個東西的時候發現全域變數在class中調用沒有值,找了很久原因,原來是因為那個類裡面的include的一個檔案裡面的值也不是全域變數,因為那個檔案是被另一個函數所include,這樣子造成類檔案裡面的include檔案的變數也是局部變數。
例子:
test008.php
include 'test009.php';Class A {var $name;function __construct() {}function A() {$this->__construct();}function test() {var_dump($GLOBALS['var']);}function test1() {$this->test();}}$a = new A();
?test009.php
$var = 'scnjl';
?test010.php
class xx {function __construct() {}function test() {include 'test008.php';$a->test1();}}$xx = new xx();$xx->test();
?這個只是做個簡單列子,其實test009.php裡面的值是可以直接放到test008.php中的。
這裡輸出一個null。