Hans123 Hans123 - 1 year ago 63
PHP Question

Defining custom superglobal array in PHP

How can I define a superglobal array in PHP?

I know that there is no way to do this. However I thought there might be some "brains" out there knowing about a workaround for it. Specifically I want to have an array on every .php file I have that has the same data. I also want to access it like this:

echo $_HANS["foo"];


if( isset($_HANS["foo"]) && !empty( $_HANS["foo"] ) ) // DO

Important for me is that I don't want to have a static class, where I have to access my members like this:


By now I have something like this, but I guess it's not really efficient:

define( 'HANS', serialize( array( 'FooKey' => 'FooData' ) ));

To access it I have to unserialize it. Storing the data in a variable and THEN I can work with the index-operators.

$_HANS = array();
foreach(unserialize(HANS) as $Key => $Data)
$_HANS[$Key] = $Data;
echo $_HANS["FooKey"];

There must be a way to skip this whole foreach-stuff in every single file.

EDIT =======================================

Okay, so by now I have this little workaround, which should be a little more efficient, than including a whole new file. However I'm still listening for a better solution :)

I simply put this code above in a global function:

function getData()
$_DATA = array();
foreach( unserialize(HANS) as $Key => $Data )
$_DATA[$Key] = $Data;
return $_DATA;

An everything I have to do is to put this line of code in every .php-file:

$_HANS = getData();

The problem about php.ini is the compatibility with companies offering 'webhosting'. They often give you a predefined installation of Apache, PHP, MySQL and Perl (often: LAMP) and don't allow you to edit the php.ini file.

Answer Source

You can declare $myArray at the beginning of the script (you can use a prepend file), and then access it using $GLOBALS['myArray'] from any point after that.