Jump to content

[SOLVED] Question about using global.


OM2

Recommended Posts

I've read that using global is a big no no.

And instead, you should use variables and pass them into functions.

 

I have declared an array, $myVariables, in which I store all of my variables that I want functions to access.

 

I wanted to know, is it 'OK' if I use:

global $myVariables;

 

Just wanted to know if it's good practice or not.

I find that having to pass in the extra arguement of the global variable array is annoying and slightly illogical because it doesn't really make sense to the function functionality.  (Not sure if that makes sense!)

 

Thanks.

 

 

OM

Link to comment
https://forums.phpfreaks.com/topic/116857-solved-question-about-using-global/
Share on other sites

Personally I think using globals is very easy and convenient, for example you could do:

 

$array = array('stuff1', 'stuff2');

 

And

 

function myFunction() {

    global $array;

}

 

With it it just means that for the sake of that function it will pull the $array variable from outside the script. Very helpful and convienent. For example, if you used the previously said statement 100 times throughout your mega web script and then one day you need to add one more array to be globally included for the function. You'd only have to add one more line of code inside the function.

 

If you were to do

 

myFunction($array); every single time you wanted to call the function so that it always included the $array, it could get quite cluttered and complicated later on if you are already including 5 or 6 variables when using the function and 1 week later you need to add that array. Would you rather modify every single call to myFunction or simply add one line inside the function itself.

i'll do as u suggest for future.

 

Don't. The method you have used (passing the array into the function) should always be the preffered method.

 

Using the global keyword makes it harder to decifer where exactly this magical variable is defined, it also makes it easier to be overidden accidently.

I'll echo what thorpe has already stated. Don't use the global keyword to bring variables into a function.

 

If your function is that closely tied to specific variables, you should be using an OOP class to wrap both the variables and the function together or the code you are trying to make into a function is main program logic and is inappropriate to be in a function at all.

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.