Jump to content

How to use an array as a global variable, and include it without reinitializing?


karma-lab

Recommended Posts

I think there's something I'm missing about php in general (being a C/C++ programmer mainly) ;). But what I want to do is this:

 

1. Declare or define an empty array in an include file (my_include.php).

2. Include that file (my_include.php) in another file and call a function that fills the array with values.

3. Include that file (my_include.php) in a third file and call a function that reads values out of the array.

 

No matter how I try to do this, including it the second time seems to erase the values in the array. I'm thinking I must be missing some syntax or grasp of some basic concept...

 

It's difficult to break this down into a simple example because I'm attempting to do this within the confines of some php BBS software, but the general idea would be something like:

 

===== file: my_include.php

//declare a variable
$my_array;
// OR:
// $my_array = array ();
// OR:
// $my_array = NULL;

===== file_1.php

include ('my_include.php');

function do_setup() 
{
global $my_array;
for ($i = 0; $i < 10; $i++)
{
	$my_array[$i] = $i;
}
}

===== file_2.php

include ('my_include.php');

function read_values() 
{
global $my_array;
for ($i = 0; $i < 10; $i++)
{
	echo "value " . $my_array[$i];
}
}

 

Within the BBS code, it appears that the scope of the places where the two different functions are called to fill and read from the array are such that I cannot pass global variables between them, hence trying to use an include file. Any ideas would be appreciated, including telling me how stupid I'm being. ;)

 

Edit: should have mentioned its PHP 5.2.5.

 

including a file does not cause variable persistence across scripts (pages). if you need to maintain data across scripts, i suggest using a session and session variables.

That's precisely the kind of basic concept that I knew I was missing. ;)  Thanks, I'll have to read up on that.

Just think of each request as being a completely new start.

 

Once the user browses away from a page, all the variables are destroyed, except for session/cookie and any new post/get methods from a form.

 

Where in C you have an entire environment which exists constantly from the start to end of the session, in PHP we have to store it in a session variable, cookie or database between pages, then get it again.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.