php在函数内使用全局变量

在php中,如果在函数内部要使用全局变量的话,要先用global声明该变量,

<?php  
$x=10;  
$y=20;  
function test(){ 
	global $x,$y;	//如果要在函数内使用全局变量,则必须用global声明。
    $y=$x+$y;
	echo $y;  //输出30
}  
test();
echo $y;//输出30  
?>

如果不用global声明,则会发生undefined variable错误。

另外一种方法:

声明的全局变量会保存在$GLOBALS这个超全局变量中,可以在php的任意处用$GLOBALS[index]来访问已经声明过的全局变量,其中index为变量的名称

<?php  
print"<hr>";
$a=10;  
$b=20;  
function test_global(){ 
	$GLOBALS['b']+=$GLOBALS['a'];
	echo $GLOBALS['b'];  //输出30
}  
test_global();
echo $b;//输出30  
?>

参自:

点击打开链接

点击打开链接

猜你喜欢

转载自blog.csdn.net/f156207495/article/details/79066476