PHP中的全局变量的一些小结
作者:admin 日期:2012-04-07
1.两个或以上函数互相调用时的全局变量问题
$name = 'caihuafeng';
fun1();
function fun1() {
$name = 'caihf';
fun2();
echo __FUNCTION__ . " name: $name" . NEWLINE;
}
function fun2() {
global $name;
echo __FUNCTION__ . " name: $name" . NEWLINE;
}
输出如下:
fun2 name: caihuafeng
fun1 name: caihf
如果想在函数fun1中对全局变量$name的修改影响到函数func2中,则必须在函数fun1将$name定义为全局变量
$name = 'caihuafeng';
fun1();
function fun1() {
global $name;
$name = 'caihf';
fun2();
echo __FUNCTION__ . " name: $name" . NEWLINE;
}
function fun2() {
global $name;
echo __FUNCTION__ . " name: $name" . NEWLINE;
}
输出如下:
fun2 name: caihf
fun1 name: caihf
2、php中定义全局变量的几种方式
a、一种方式是在函数外面定义变量(不加$GLOBALS),在函数内部加上$GLOBALS进行调用(如debug('global1', $GLOBALS['global_test1']);)
b、一种试是在函数数外面定义变量(加$GLOBALS),,在函数内部加上$GLOBALS进行调用(如debug('global2', $GLOBALS['global_test2']);)
c、一种试是在函数数外面定义变量(不加$GLOBALS),在函数内部用global声明它为全局变量然后调用(debug('global3', $GLOBALS['global_test3']);)
$global_test1 = 'global var1';
$GLOBALS['global_test2'] = 'global var2';
$global_test3 = 'global var3';
function global_test() {
global $global_test3;
debug('function', __FUNCTION__);
debug('global1', $GLOBALS['global_test1']);
debug('global2', $GLOBALS['global_test2']);
debug('global3', $global_test3);
}
global_test();
---------------------------------------------------
$var is a string, print as string
function:|global_test|
---------------------------------------------------
---------------------------------------------------
$var is a string, print as string
global1:|global var1|
---------------------------------------------------
---------------------------------------------------
$var is a string, print as string
global2:|global var2|
---------------------------------------------------
---------------------------------------------------
$var is a string, print as string
global3:|global var3|
---------------------------------------------------
function global_test($count = 3) {
global $get_keys;
$get_keys = array();
//不能这样定义global $get_keys = array();
for ($i = 0; $i < $count; $i++) {
$get_keys[$i] = $i;
}
}
global_test();
debug($get_keys, '', 'array');
---------------------------------------------------
$var is an array, print as array
Array
(
[0] => 0
[1] => 1
[2] => 2
)
---------------------------------------------------
广告位