PHP中global與¥GLOBALS[]差別

來源:互聯網
上載者:User
PHP中global與¥GLOBALS[]區別

開發一個PHP程式,不可避免的要使用到全域資料.

全域變數便是其中之一,當然這個觀點頗具爭議,有許多人還是建議禁用全域變數,使用不當對造成程式的可讀性很差!結構混亂,調試更是一頭霧水,但是不可否認他的便捷,這便是php為什麼會用全域變數global原因吧!…

今天就遇到了php 全域變數不起作用的問題.

先上一段簡單的代碼:

1

2 $a = 0 ;

3 function Test()

4 {

5 $a =1;

6 }

7 Test();

8 echo $a;

9 ?>

上面的代碼中輸出是0,那是因為函數體Test內$a變數被預設設定為局部變數,$a的範圍就是在Test內.修改代碼如下

01

02 $a = 0 ;

03 function Test()

04 {

05 global$a;//申明函數體Test內使用的$a變數為global全域變數

06 $a=1;

07 }

08 Test();

09 echo $a;

10 ?>

申明函數體Test內使用的$a變數為global全域變數後,使得$a的作用全域,所以輸出為1.
上面的執行個體只是基本的global全域變數知識,下面我們看看複雜點的:

01 //A.php 檔案

02

03

04 function Test_Global()

05 {

06 include 'B.php';

07 Test();

08 }

09

10 $a = 0 ;

11 Test_Global();

12 echo $a;

13 ?>

14

15 //B.php 檔案

16

17

18 function Test()

19 {

20 global$a;//申明函數體Sum內使用的$a變數為global全域變數

21 $a=1;

22 }

23 ?>

為什麼輸出的卻是0?!!

在使用者自訂函數中,一個局部函數範圍將被引入。任何用於函數內部的變數按預設情況將被限制在局部函數範圍內(包括include 和 require 匯入的檔案內的變數)!
解釋:A.php檔案的內Test_Global是定義好的第三方函數,該函數用include匯入了B.php檔案內的$a的global全域變數,所以$a被限制在Test_Global局部函數範圍內,所以B.php檔案內的$a的作用範圍都在Test_Global內,而不是作用了整個A.php內….

解決方案:

1. 衝出局部函數

01 //A.php 檔案

02

03

04 function Test_Global()

05 {

06 Test();

07 }

08 include 'B.php'; //將include 從局部Test_Global函數中移出

09 $a = 0 ;

10 Test_Global();

11 echo $a;

12 ?>

13

14 //B.php 檔案

15

16

17 function Test()

18 {

19 global$a;

20 $a=1;

21 }

22 ?>

2.優秀的訪問器

1 //A.php 檔案

01

02 include 'B.php';

03 $a =0;

04 Set_Global($a);

05 echo $a;

06 ?>

07

08 //B.php 檔案

09

10

11 function Set_Global(&$var)

12 {

13 $var=1;

14 }

15 ?>
  • 聯繫我們

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