Home  >  Article  >  Backend Development  >  php中的global及GLOBALS的一些有关问题

php中的global及GLOBALS的一些有关问题

WBOY
WBOYOriginal
2016-06-13 11:01:151047browse

php中的global及GLOBALS的一些问题

首先看一个简单例子

$a = 'scnjl';function test() {	global $a;	unset($a);}test();var_dump($a);function test1() {	unset($GLOBALS['a']);}test1();var_dump($a);

?这里输出的结果是:

string(5) "scnjl" NULL

可以看到其实global在函数中使用的时候,并没有直接用到变量$a,而是复制了一个指向$a的值的变量,所以当unset以后,全局变量$a并没有被unset,而$GLOBALS['a']直接代表了全局变量$a。

这是global 和 GLOBALS的区别吧。

?

今天在弄一个东西的时候发现全局变量在class中调用没有值,找了很久原因,原来是因为那个类里面的include的一个文件里面的值也不是全局变量,因为那个文件是被另一个函数所include,这样子造成类文件里面的include文件的变量也是局部变量。

例子:

test008.php

include 'test009.php';Class A {	var $name;	function __construct() {	}	function A() {		$this->__construct();	}	function test() {		var_dump($GLOBALS['var']);	}	function test1() {		$this->test();	}}$a = new A();

?test009.php

$var = 'scnjl';

?test010.php

class xx {	function __construct() {	}		function test() {		include 'test008.php';		$a->test1();	}}$xx = new xx();$xx->test();

?这个只是做个简单列子,其实test009.php里面的值是可以直接放到test008.php中的。

这里输出一个null。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn