params vs globals

I am having a bit of trouble trying to figure out the best way to do something and I’m hoping for some opinions.

I have a function that will be called multiple times (possible over a hundred) from a while loop. Basically, it is part of a search function. There are some unchanging variables in this function that will be used over and over again, that help describe the object I am looking for. Currently there are three of these types of variables, as well as a priority queue object that changes with each call to the function and an object used to access a database. I am wondering if it is better coding style to pass these variables and objects in as parameters, or just declare them as global at the top of the function. Normally I would side on passing them in as parameters, but this would be the same 5 parameters being passed in over and over again. I’m not sure if there is any performance gain or loss (or if it matters) from declaring global vs passing in parameters or if using globals is just plain evil.

Thanks for any advice

Global is not evil by nature, but generally provides more access than you bargained for, and can be a serious pain to debug, should anything go wrong (especially when you use functions included from other pages). The unchanging variables, are these like constants? If so, perhaps it’s better to define them in local variables inside the function, so their scope extends to only the function scope and not beyond. Variables that are not set in stone with each function call are generally passed as parameters. Variables that are ‘in-betweens’, for example a database connection object, can be made global. It is highly recommended however, to give global variables a value only once throughout the entire execution of your scripts and to not change it afterwards. Changing global variables inside functions is very definately evil by nature ;) (unless of course the function is built specifically to initiate this variable)

Thanks for your reply Zyppora!

Sponsor our Newsletter | Privacy Policy | Terms of Service