Let me start by explaining.
I have a few global database connections and have a few simple functions that use each one and perform queries and such.
Because i want to use the connections more then once, and to save me defining them each time in each function i have created them as globals at the top of the document.
However i am just wondering that instead of having to write
global $mysql_db1, $mysql_db2, $mysql_db3, $mysql_db4, $mysql_db5;
Is there anyway to make this happen without me having to copy and paste it each time?
I know its trivial but i just wanted to speed up my own development,
Globals are usually regarded as bad practice. I won’t pontificate at you about it, but check out this article: http://blog.case.edu/gps10/2006/07/22/why_global_variables_in_php_is_bad_programming_practice
You can use the
$GLOBALSsuperglobal to access any variable that has been defined in the global scope (docs). Thus, in your example code, simply using$GLOBALS['mysql_db1']would be the equivalent of having the lineglobal $mysql_db1;and then using$mysql_db1.I cannot stress enough (without pontificating) how bad of a plan this is. YOU might be all right with it the entire time you’re developing, but poor poor Johnny Nextguy, and may the Gods of Code save you if you include a third-party script that also uses globals… and there’s a conflict of variable names. Now you’re in for it!
As has been suggested, you are better off encapsulating your database functionality in a class. If you use a static class, you still have all the benefits of a global variable without a polluted scope or danger of overwriting.
Here is a sample database class, along with usage: