时间:2021-05-18
测试代码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的情况,就觉得有点郁闷了.
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了php多次include后导致全局变量global失效的解决方法。分享给大家供大家参考。具体分析如下:在多个文件中,文件一个接一个include,
include_once("./comm/Smarty.class.php");//包含smarty类文件$smarty=newSmarty();//建立sma
PHP中$GLOBALS和global都可以实现全局变量的功能,所以很多人都认为global和$GLOBALS[]只是写法上面的差别,其实不然。$GLOBALS
传统上,在PHP里,当我们要用到一个class文件的时候,我们都得在文档头部require或者include一下:
打开/include/dedevote.class.php文件,查找$this->dsql->ExecuteNoneQuery("UPDATE`dede_vot