我是靠谱客的博主 喜悦钢铁侠,最近开发中收集的这篇文章主要介绍在class的function中include的文件中,非php的global全局环境,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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


最后

以上就是喜悦钢铁侠为你收集整理的在class的function中include的文件中,非php的global全局环境的全部内容,希望文章能够帮你解决在class的function中include的文件中,非php的global全局环境所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(35)

评论列表共有 0 条评论

立即
投稿
返回
顶部