PHP Global定義全域變數使用說明

來源:互聯網
上載者:User

很不習慣PHP中的變數範圍,PHP中函數變數和全域是完全隔絕的,也就是無法相互訪問。
比如下面這樣:

copytext

 代碼如下 複製代碼

$test = 123;

 abc(); //這裡什麼都不輸出,因為訪問不到$test變數
function abc(){
    echo($test);
}$test = 123;

abc(); //這裡什麼都不輸出,因為訪問不到$test變數
function abc(){
    echo($test);

}如果,你想在函數內部訪問外部變數,你需要這樣:

copytext

 代碼如下 複製代碼

$test = 123;

 abc(); //輸出123
function abc(){
    global $test;
    echo($test);
}$test = 123;

abc(); //輸出123
function abc(){
    global $test;
    echo($test);
}

但如果我們在函數中定義全域變數呢,像下面這樣:

copytext

 代碼如下 複製代碼
function abc(){
    global $test;
    $test = 123;
}
abc();
echo($test); //輸出123function abc(){
 global $test;
 $test = 123;
}
abc();
echo($test);

 //輸出123通過這種方式,我們可以在外部存取到函數內部定義的變數

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

解決方案:
1. 衝出局部函數

 //A.php 檔案

 代碼如下 複製代碼

<?php
function Test_Global()
{&nbsp;&nbsp;
    Test();&nbsp;&nbsp;
}&nbsp;&nbsp;
include 'B.php';&nbsp;&nbsp; //將include 從局部Test_Global函數中移出
$a = 0 ;
Test_Global();
echo $a;
?>&nbsp;

//B.php 檔案

<?php
function Test()
{
    global $a;
    $a =1;
}
?>

2.優秀的訪問器

 代碼如下 複製代碼

//A.php 檔案
<?php
include 'B.php';&nbsp;
$a =0;
Set_Global($a);
echo $a;
?>&nbsp;

//B.php 檔案

<?php
function Set_Global(&$var)
{
    $var=1;
}
?>

相關文章

聯繫我們

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