php中的global及GLOBALS的一些有關問題

來源:互聯網
上載者:User
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。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.