-1

I tried the following code to create a superglobal variable using $GLOBALS.

test.php

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

Here is the test3.php

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

The output i get is

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

The $GLOBAL['test'] is not getting set.

But when I try var_dump in test.php,I find $GLOBAL array to have a key 'test' with value 'hello'.

What is the reason of this behaviour?

Also I wish to create a superglobal database connection object using the $GLOBAL.Is it recommended?

rjv
  • 4,841
  • 3
  • 26
  • 47
  • No to both. Don't use globals, and you don't need statics / globals for your DB. You'll find plenty of questions that deal with this on SO, just use the search – JohnP Mar 09 '12 at 18:11
  • Heh, please, before asking, learn at least the basics of the language. You would have soon found out that PHP does not reuse variables between requests. – NikiC Mar 09 '12 at 18:13
  • I expected all superglobals behave just like $_SESSION[ ] – rjv Mar 09 '12 at 18:16
  • [... That's because variables aren't really "global" in PHP.](http://stackoverflow.com/a/1557799/345031) – mario Mar 09 '12 at 19:29

1 Answers1

1

Try using $_SESSION instead of $GLOBALS for setting stateful variables.

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

// test3.php
session_start();
var_dump($_SESSION);
?>

As far as a $GLOBAL database connection, your best bet is to read about singleton variables related to database connections. I would NOT recommend storing anything in the $GLOBALS array.

Quick google search on database singletons returned several pages, but here is a decent one.

Mike Purcell
  • 19,055
  • 9
  • 47
  • 84