php包含(include/require)檔案時的範圍

來源:互聯網
上載者:User

標籤:

當一個php指令碼被require/include時,他的變數範圍根據其上下文環境決定.

1.如果是在一個函數中require/include一個檔案,則此檔案中的變數範圍是這個函數的範圍.也就是說,這個檔案只能訪問此函數內在載入這個檔案前所定義的變數,全域變數是不能訪問的.距離說明

指令碼test.php的內容:

<?php    function foo(){        $GLOBALS[‘a‘]="i am global";        $b="i am variable inner function";        include "included-file.php";    }foo();

 

指令碼included-file.php的內容:

<?phpecho $a,$b;

運行test.php的結果是:

Notice: Undefined variable: a in E:\work\phpcom\aa.php on line 2
i am variable inner function

2.如果是在全域環境中引入一個檔案,那這個檔案是可以直接存取全域變數的.

 

php包含(include/require)檔案時的範圍

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.