php引用问题

WBOY
WBOYOriginal
2016-06-23 13:59:58812browse

<?php 	$var1 = 1;	$var2 = 2;	function test(){		global $var1, $var2;		$var1 = &$var2;		$var1 = 55;	}	test();	echo $var1.",".$var2;?>

<?php 	$var1 = 1;	$var2 = 2;	$var1 = &$var2;	$var1 = 55;	echo $var1.",".$var2;//结果是55,55?>

global到底干了些什么,$var1 = &$var2;这一句的意思是让$var1指向var2的内容吗?


回复讨论(解决方案)

global $var1, $var2;
字面意义:声明 $var1 和 $var2 是全局变量
实际动作:创建两个局部变量 $var1 和 $var2,并将他们设置为全局变量 $var1, 和 $var2 的引用

<?php     $var1 = 1;    $var2 = 2;    $var1 = &$var2;  // $var1 引用了 $var2,引用的意思是,var1指向了var2的内存地址,因此,修改var1的值,var2的值也会改变.    $var1 = 55;    echo $var1.",".$var2;//结果是55,55?><?php     $var1 = 1;    $var2 = 2;    function test(){        global $var1, $var2; // $var1 与 $var2 引用了全局变量 $var1 与 $var2的值        $var1 = &$var2; // $var1 引用了 $var2的值,执行这句后,$var1与$var2指向的内存地址都是同一个.因为$valr引用$var2后,$var1就不再指向全局变量$var1,而是指向了全局变量$var2        $var1 = 55; // 局部变量 $var1 与全局变量 $var2的值都改为55,    }    test();    echo $var1.",".$var2; // 因为执行$var1=55之前,function 内的$var1已经不是指向全局变量$var1,因此,全局变量$var1的值没有改变,都是1,而全局变量$var2改变了,所以是55?>

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