Jump to content

Accessing an Outside Array Inside a Function


drewjoh

Recommended Posts

Hi all,

 

I have the beginning of my script starting like this:

 

include('startup.php');
include('functions.php');
connect_db();

 

In my startup.php code, I have an array created called $Settings[] with my database information (username, password, database, etc).

 

In functions.php, I have a function called connect_db() which connects to the database. The problem is, the connect_db() function can't seem to access the $Settings array, though I can access it outside the function in the script. Accessing outside variables never seemed to be a problem before (or maybe I just never have needed to access an outside variable?). From what I understand on php.net it's supposed to be possible... or maybe I'm really wrong?

If you don't pass the array to the function as a parameter, you need to declare it global inside the funciton.

 

Either

<?php
$Settings = array('abnd','ccc','tttt');
connect_db($Settings);

function connect_db($Settings){

}
?>

or

<?php
connect_db();

function connect_db() {
    global $Settings;


}
?>

 

Ken

Try and avoid using global in functions. This is because you could have a function worth 10, 000 lines then you realise you need a global variable. But the global variable also shares the name of a variable in your function! And the names would conflict, same variable name - different values...

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.