$GLOBAL关联数组在页面重定向时重置


$GLOBAL associative array getting reset on page redirection

我尝试了以下代码来使用$GLOBALS创建一个超全局变量。

test.php

<?php
    $GLOBALS['test']='hello';
    header("location:test3.php");
?>

这是test3.php

<?php
    var_dump($GLOBALS);
    echo $GLOBALS['test'];
?>

我得到的输出是

array(5) { ["GLOBALS"]=> *RECURSION* ["_POST"]=> array(0) { } ["_GET"]=> 
array(0) { }["_COOKIE"]=> array(1) {"PHPSESSID"]=>string(26)"oer267anbfrrhtj64lpqrocdd3"} 
["_FILES"]=> array(0) { } }  

$GLOBAL["测试"]未设置。

但当我在test.php中尝试var_dump时,我发现$GLOBAL数组有一个值为"hello"的键"test"。

这种行为的原因是什么?

此外,我希望使用$GLOBAL创建一个超级全局数据库连接对象。建议使用吗?

尝试使用$_SESSION而不是$GLOBALS来设置有状态变量。

<?php
session_start();
$_SESSION['test'] = 'hello';
header("location:test3.php");
// test3.php
session_start();
var_dump($_SESSION);
?>

对于$GLOBAL数据库连接,您最好阅读与数据库连接相关的单例变量。我不建议在$GLOBALS数组中存储任何内容。

在数据库singletons上快速谷歌搜索返回了几个页面,但这里有一个不错的页面。