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

yipeiwu_com5年前PHP代码库
测试代码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的情况,就觉得有点郁闷了.

相关文章

仿AS3实现PHP 事件机制实现代码

复制代码 代码如下: <?php /** * 事件异常 * * @author lonely * @create 2010-10-21 * @version 0.1 * @last...

PHP数据类型的总结分析

PHP共有8中数据类型: 类型名称 类型表示 取值 bool 布尔型 true,false integer 整型 -2147483647-2147483648 string...

php使用scandir()函数扫描指定目录下所有文件示例

本文实例讲述了php使用scandir()函数扫描指定目录下所有文件。分享给大家供大家参考,具体如下: //遍历子文件夹和文件夹的内容 并且计算出文件的多少 //一个demo 引号替...

非常重要的php正则表达式详解

 正则表达式是php中一个非常重要的知识点,通常用来查找和替换字符串,最常用的就是验证用户输入的信息格式是否正确,如邮件格式、电话格式等等。还有比如采集器之类的软件中,正则也是...

简单的PHP多图上传小程序代码

先上源代码,你可以copy到自己的电脑上去运行~ 复制代码 代码如下: <html> <meta http-equiv="Content-Type" content="...