实测在class的function中include的文件中非php的global全局环境

前端之家收集整理的这篇文章主要介绍了实测在class的function中include的文件中非php的global全局环境前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

测试代码1.PHP
<div class="codetitle"><a style="CURSOR: pointer" data="47369" class="copybut" id="copybut47369" onclick="doCopy('code47369')"> 代码如下:

<div class="codebody" id="code47369">
<?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 => ',$gg2);
echo "\n--- ----\n";

代码2.PHP
<div class="codetitle"><a style="CURSOR: pointer" data="39083" class="copybut" id="copybut39083" onclick="doCopy('code39083')"> 代码如下:
<div class="codebody" id="code39083">
<?PHP
$g2 = 'g2';
global $gg2;//本环境下并非全局,需要提升
$gg2 = 'gg2';
function g2fun() {
global $g1,$g2,$gg2;
echo "\n--- in g2fun ----\n";
var_dump('$g1 => ',$g1,$gg2);
echo "\n--- ----\n";
}
g2fun();
echo "\n--- in 2.PHP ----\n";
var_dump('$g1 => ',$gg2
);
echo "\n--- ----\n";
global $g1;
echo "\n--- in 2.PHP global----\n";
var_dump('$g1 => ',$gg2
);
echo "\n--- ----\n";

结果
<div class="codetitle"><a style="CURSOR: pointer" data="17056" class="copybut" id="copybut17056" onclick="doCopy('code17056')"> 代码如下:
<div class="codebody" id="code17056">
--- 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的情况,就觉得有点郁闷了.

globalglobalincludeincludeinclude全局环境

猜你在找的PHP相关文章