程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 實測在class的function中include的文件中非php的global全局環境

實測在class的function中include的文件中非php的global全局環境

編輯:關於PHP編程
    正如標題所言經測試的結果為:在class中include後,被include文件變量域已經變成func中了,非全局.但是可以通過global提升,感興趣的朋友可以參考下哈,希望對大家有所幫助  

    測試代碼1.php

    復制代碼 代碼如下:
    <?php
    $g1 = 'g1';
    class c{
    function fun() {
    include('2.php');
    echo "n-----in class fun---n";
    global $g1;
    var_dump("$g1 => ", $g1
    ,'$g2 => ', $g2
    ,'$gg2 => ', $gg2
    );
    echo "n--------n";
    }
    }
    c::fun();
    echo "n--- in 1.php ----n";
    var_dump('$g1 => ', $g1
    ,'$g2 => ', $g2
    ,'$gg2 => ', $gg2);
    echo "n--- ----n";


    代碼2.php

    復制代碼 代碼如下:
    <?php
    $g2 = 'g2';
    global $gg2;//本環境下並非全局,需要提升
    $gg2 = 'gg2';
    function g2fun() {
    global $g1, $g2, $gg2;
    echo "n--- in g2fun ----n";
    var_dump('$g1 => ', $g1, '$g2 => ', $g2
    , '$gg2 => ', $gg2);
    echo "n--- ----n";
    }
    g2fun();
    echo "n--- in 2.php ----n";
    var_dump('$g1 => ', $g1, '$g2 => ', $g2
    , '$gg2 => ', $gg2
    );
    echo "n--- ----n";
    global $g1;
    echo "n--- in 2.php global----n";
    var_dump('$g1 => ', $g1, '$g2 => ', $g2
    , '$gg2 => ', $gg2
    );
    echo "n--- ----n";


    結果

    復制代碼 代碼如下:
    --- in g2fun ----
    string(7) "$g1 => "
    string(2) "g1"
    string(7) "$g2 => "
    NULL
    string(8) "$gg2 => "
    string(3) "gg2"
    --- ----
    --- in 2.php ----
    string(7) "$g1 => "
    NULL
    string(7) "$g2 => "
    string(2) "g2"
    string(8) "$gg2 => "
    string(3) "gg2"
    --- ----
    --- in 2.php global----
    string(7) "$g1 => "
    string(2) "g1"
    string(7) "$g2 => "
    string(2) "g2"
    string(8) "$gg2 => "
    string(3) "gg2"
    --- ----
    -----in class fun---
    string(7) "$g1 => "
    string(2) "g1"
    string(7) "$g2 => "
    string(2) "g2"
    string(8) "$gg2 => "
    string(3) "gg2"
    --------
    --- in 1.php ----
    string(7) "$g1 => "
    string(2) "g1"
    string(7) "$g2 => "
    NULL
    string(8) "$gg2 => "
    string(3) "gg2"
    --- ----


    由此可見,
    在class中include後,被include文件變量域已經變成func中了,非全局.
    但是可以通過global提升.
    一般被include文件在編寫時,可能會由於沒有注意到被include的情況,就覺得有點郁悶了.

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved