熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> PHP編程 >> 正文

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

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

  測試代碼php

復制代碼 代碼如下:
<?php
$g = g;
class c{
function fun() {
include(php);
echo "nin class funn";
global $g;
var_dump("$g => " $g
$g => $g
$gg => $gg
);
echo "nn";
}
}
c::fun();
echo "n in php n";
var_dump($g => $g
$g => $g
$gg => $gg);
echo "n n";

  
代碼php

復制代碼 代碼如下:
<?php
$g = g;
global $gg;//本環境下並非全局需要提升
$gg = gg;
function gfun() {
global $g $g $gg;
echo "n in gfun n";
var_dump($g => $g $g => $g
$gg => $gg);
echo "n n";
}
gfun();
echo "n in php n";
var_dump($g => $g $g => $g
$gg => $gg
);
echo "n n";
global $g;
echo "n in php globaln";
var_dump($g => $g $g => $g
$gg => $gg
);
echo "n n";

  
結果

復制代碼 代碼如下:
in gfun
string() "$g => "
string() "g"
string() "$g => "
NULL
string() "$gg => "
string() "gg"

in php
string() "$g => "
NULL
string() "$g => "
string() "g"
string() "$gg => "
string() "gg"

in php global
string() "$g => "
string() "g"
string() "$g => "
string() "g"
string() "$gg => "
string() "gg"

in class fun
string() "$g => "
string() "g"
string() "$g => "
string() "g"
string() "$gg => "
string() "gg"

in php
string() "$g => "
string() "g"
string() "$g => "
NULL
string() "$gg => "
string() "gg"

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


From:http://tw.wingwit.com/Article/program/PHP/201311/21095.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.