PHP中函数内引用全局变量的方法
作者:
PHP函数内引用全局变量的解决方法
先看下面的代码:
<?php
$var1 = "#####";
$var2 = "&&&&&";
function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =&$var1; //1
} else {
$GLOBALS["var2"] =&$var1; //2
}
}
global_references(false);
echo "var2 is set to '$var2'<br/>";
global_references(true);
echo "var2 is set to '$var2'<br/>";
?>
输出的结果如下:
var2 is set to '&&&&&'
var2 is set to '#####'
可见,上面的代码中:
$var2 =&$var1; //1
只对函数内部可见。
而
$GLOBALS["var2"] =&$var1; //2
在全局范围内可见。
复制代码 代码如下:
<?php
$var1 = "#####";
$var2 = "&&&&&";
function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =&$var1; //1
} else {
$GLOBALS["var2"] =&$var1; //2
}
}
global_references(false);
echo "var2 is set to '$var2'<br/>";
global_references(true);
echo "var2 is set to '$var2'<br/>";
?>
var2 is set to '&&&&&'
var2 is set to '#####'
可见,上面的代码中:
$var2 =&$var1; //1
只对函数内部可见。
而
$GLOBALS["var2"] =&$var1; //2
在全局范围内可见。