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

WBOY
發布: 2016-07-21 15:00:44
原創
771 人瀏覽過

测试代码1.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
复制代码 代码如下:

$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的情况,就觉得有点郁闷了.

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/328040.htmlTechArticle测试代码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...
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!