drewjoh Posted February 22, 2007 Share Posted February 22, 2007 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? Link to comment https://forums.phpfreaks.com/topic/39595-accessing-an-outside-array-inside-a-function/ Share on other sites More sharing options...
kenrbnsn Posted February 22, 2007 Share Posted February 22, 2007 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 Link to comment https://forums.phpfreaks.com/topic/39595-accessing-an-outside-array-inside-a-function/#findComment-191092 Share on other sites More sharing options...
drewjoh Posted February 22, 2007 Author Share Posted February 22, 2007 Thanks for your reply Ken! Declaring it global in the function worked. Upon more thinking though, I can see how that could be bad programming practice, and how passing the values is better. Thanks! Link to comment https://forums.phpfreaks.com/topic/39595-accessing-an-outside-array-inside-a-function/#findComment-191107 Share on other sites More sharing options...
heckenschutze Posted February 22, 2007 Share Posted February 22, 2007 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... Link to comment https://forums.phpfreaks.com/topic/39595-accessing-an-outside-array-inside-a-function/#findComment-191112 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.